<?php

namespace App\Services;

use App\Entities\PermissionRole;
use App\Facades\Message;
use App\Models\AssessmentOnlineInformation;
use App\Models\AssessmentReqConfirm;
use App\Models\AssessmentUserAcceptance;
use App\Models\BpmArchivedData;
use App\Models\BpmUserToDo;
use App\Models\OriginalFormatDocHardware;
use App\Models\SOriginalFormatHardwareServer;
use App\Models\User;
use App\Models\Unit;
use App\Models\Person;
use App\Models\FormatDoc;
use App\Models\BpmMaindata;
use Illuminate\Support\Str;
use App\Models\BpmFormatdoc;
use App\Models\BpmOrgDeptList;
use App\Models\BpmOrgUserList;
use App\Models\BpmInsUserList;
use App\Models\BpmInsremarklist;
use App\Models\RSystemPersonRole;
use App\Models\AssReqFunctionList;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Models\AssessmentOaDocking;
use Mtownsend\XmlToArray\XmlToArray;
use App\Models\AssessmentReqDevSpilt;
use App\Models\SOriginalFormatModuleContent;
use App\Models\ViewOrguserwithmaindept;
use Ramsey\Uuid\Uuid;
use Spatie\ArrayToXml\ArrayToXml;

class ListService extends BaseService
{
    /**
     * @var 用户名
     */
    public $username;

    /**
     * @var 单位id
     */
    public $unitId;

    /**
     * 获取到后继节点信息
     * @param string $id
     * @return array
     */
    public function getNode(string $id): array
    {
        try{
            $currentNodeId = BpmUserToDo::where('WF_OrUnid',$id)
                ->where('Userid',$this->getUsername())
                ->where('WF_Status','Current')
                ->value('Nodeid');

            if (empty($currentNodeId)){
                return customer_return_error('当前服务单节点数据不存在');
            }

            $service = new \SoapClient(config('node.nodeUlr'));

            $result = $service->runRule([
                'rulenum' => 'R_S017_B107',
                'params'  => json_encode([
                    'nodeId'  => $currentNodeId,
                    'docUnid' => $id
                ]),
                'userid' => 'app',
                'sysid'  => 'pms',
                'syspwd' => 'pms'
            ]);


            $result = $result->return;

            if ($result = json_decode($result,true)){
                if ($result['status'] == 200) {
                    $data = $result['data'] ?? [];

                    $data = array_filter($data,function ($item){
                        return !empty($item);
                    });

                    $data = array_values($data);

                    return customer_return_success('success',$data);
                }

                return customer_return_error($result['msg']);
            }

            return customer_return_error('数据异常',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('it 服务单 node获取异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 扭转当前节点
     * @param array $parameters
     * @return array
     */
//    public function handleNode(array $parameters) : array
//    {
//        try{
//            $currentNodeId = $parameters['node_id'] ?? '';
//
//            if (empty($currentNodeId)){
//                return customer_return_error('当前服务单节点数据不存在');
//            }
//
//            $data = [
//                'nodeId' => $parameters['target_node_id'],   //下一节点ID
//                'userId' => $parameters['user_id'],          //审批人
//                'remark'     => $parameters['remark'],       //备注
//                'docUnid'    => $parameters['server_id'],   //服务单ID
//                'currentNodeid' => $currentNodeId,          //当前节点
//            ];
//
//            $nodeService = new NodesService();
//
//            return array_merge($nodeService->handle($currentNodeId,$data),[
//                'data' => []
//            ]);
//        }catch (\Exception $exception){
//            Log::channel('api')
//                ->info('it 服务单 node节点扭转异常：'.$exception->getMessage());
//
//            report($exception);
//
//            return customer_return_error('数据异常，请稍后再试');
//        }
//    }

    public function handleNode(array $parameters) : array
    {
        try{
            $currentNodeId = $parameters['current_node_id'] ?? '';

            $userid =  auth('api')->user()->username;

            if(isset($parameters['user_id'])){
                //在硬件评估确认需要用到此信息
                $targetUserId = $parameters['user_id'].'$'.$parameters['target_node_id'];
            }else{
                $targetUserId = '';
            }

            if (empty($currentNodeId)){
                return customer_return_error('当前服务单节点数据不存在');
            }

            $data = [
                'nodeId' => $parameters['target_node_id'],   //下一节点ID
                'userId' => $userid,                         //当前审批人
                'remark'     => $parameters['remark'],       //备注
                'docUnid'    => $parameters['server_id'],    //服务单ID
                'currentNodeid' => $currentNodeId,           //当前节点
                'targetUserid'  => $targetUserId,            //下一节点审批人
            ];

            $service = new \SoapClient(config('node.nodeUlr'));

            $result = $service->runRule([
                'rulenum' => 'R_S017_B108',
                'params'  => json_encode($data),
                'userid' => 'app',
                'sysid'  => 'pms',
                'syspwd' => 'pms'
            ]);

            $result = $result->return;

            if ($result = json_decode($result,true)){
                if ($result['status'] == 200) {
                    return customer_return_success($result['mag']);
                }
                return customer_return_error($result['mag']);
            }

            return customer_return_error('数据异常',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('it 服务单 node节点扭转异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     *  获取网络硬件评估审批人
     * @param array $parameters
     * @return array
     */
    public function hardwareApprover() : array
    {
        try{

            $data = DB::connection("bpm_rs")
                ->select("SELECT CnName as username,Userid as user_id FROM view_orguserwithmaindept  WHERE FolderName = '网络及软硬件团队'");

            if (empty($data)){
                return customer_return_error('网络硬件评估审批人获取异常');
            }

            return customer_return_success('success',$data);;

        }catch (\Exception $exception){
            Log::channel('api')
                ->info('it 服务单 网络硬件评估审批人获取异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 需求评估审核节点，保存自定义节点保存的审批路线
     * @param array $parameters
     * @return array
     */
    public function customApproverUpdate(array $parameters): array
    {
        try {
            //该节点默认四个操作流程
            $currNodeList = ['','需求评估汇总','网络出硬件评估','返回系统工作量评估','返回需求分解'];

            $xmlData = BpmMaindata::where('WF_OrUnid',$parameters['server_id'])
                ->value('XmlData');

            if (empty($xmlData)) {
                return customer_return_error('server_id 异常');
            }

            $data = $this->formatXml($xmlData);

            //设置自定义 审批信息
            $data['next_point'] =  $parameters['next_point'] ?? '';
            $data['next_point_show'] =  $currNodeList[$parameters['next_point']] ?? '';

            $xml = $this->formatArray($data);

            BpmMaindata::where('WF_OrUnid',$parameters['server_id'])
                ->update([
                    'XmlData' => $xml
                ]);

            return customer_return_success('success');
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 需求评估审核节点 节点操作异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * 获取到username
     * @return string
     */
    public function getUsername() : string
    {
        if (is_null($this->username)) {
            $this->username = auth('api')->user()->username ?? '';
        }

        return $this->username;
    }

    /**
     * 获取到用户的团队id
     * @return int
     */
    public function getUnitId() : int
    {
        if (is_null($this->unitId)){
            $person = auth('api')->user()->person;

            if (is_null($person)) {
                $this->unitId = 0;

                return $this->unitId;
            }

            $this->unitId = $person->unit_id ?? 0;
        }

        return $this->unitId;
    }

    /**
     * 获取到IT 服务单的列表数据
     * type 表示列表类型
     * 1 表示我的
     * 2 表示我的团队
     * 3 表示全部
     * @param int $type
     * @param array $parameters
     * @return array
     */
    public function getList(int $type,array $parameters) : array
    {
        try{
            switch ($type){
                case 1:
                    $data = $this->getNeedDealServiceList($this->getUsername(),$parameters);
                    break;
                case 2:
                    $data = $this->getNeedDealGroupServiceList($this->getUsername(),$parameters);
                    break;
                default:
                    $data = $this->getNeedDealAllServiceList($this->getUsername(),$parameters);
            }

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('it 服务单 列表数据 异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 我的服务单数据
     * @param string|null $username
     * @param array $parameters
     * @return array
     */
    public function getNeedDealServiceList(string $username = null,array $parameters = []) : array
    {
        $username = $username ?: $this->getUsername();

        if (empty($username)) {
            return [];
        }

        $taskIdArray = AssessmentUserAcceptance::where('add_wait_name',$username)
            ->distinct()
            ->where('is_wait',1)
            ->pluck('add_wait_task_id')
            ->toArray();

        return BpmUserToDo::filter($parameters)
            ->where('Userid',$username)
            ->whereNotIn('Taskid',$taskIdArray)
            ->select([
                'WF_OrUnid',
                'Subject',
                'WF_DocCreated',
                'WF_ProcessName',
                'NodeName',
                'Nodeid'
            ])
            ->orderBy('StartTime','Desc')
            ->paginate(30)
            ->map(function ($item){
                return [
                    'id'        => $item->WF_OrUnid,
                    'subject'   => $item->Subject,
                    'title'     => $item->WF_ProcessName,
                    'date'      => date('Y-m-d',strtotime($item->WF_DocCreated)),
                    'node_name' => $item->NodeName,
                    'node_id'   => $item->Nodeid
                ];
            })
            ->toArray();
    }

    /**
     * 我的团队服务单
     * @param string|null $username
     * @param array $parameters
     * @return array
     */
    public function getNeedDealGroupServiceList(string $username = null,array $parameters = []) : array
    {
        $username = $username ?: $this->getUsername();

        if (empty($username)) {
            return [];
        }

        $isLeader = Unit::where('unit.parent_id', 375)
            ->where('unit.is_deleted', 0)
            ->leftJoin('pms.person as p', 'p.unit_id', '=', 'unit.id')
            ->leftJoin('pms.r_person_post as rpp', 'p.id', '=', 'rpp.person_id')
            ->leftJoin('pms.user as us', 'us.person_id', '=', 'p.id')
            ->where('rpp.post_id', '!=', 9)
            ->where('p.is_deleted', 0)
            ->where('us.username', $username)
            ->exists();

        if(!$isLeader){
            return [];
        }

        if (!empty($this->getUnitId())) {
            $personIdArray = Person::where('unit_id',$this->getUnitId())
                ->pluck('id')
                ->toArray();

            $usernames = User::whereIn('person_id',$personIdArray)
                ->pluck('username')
                ->toArray();
        }

        $usernames = $usernames ?? [];

        if (empty($usernames)) {
            $usernames = [$username];
        }

        $taskIdArray = AssessmentUserAcceptance::whereIn('add_wait_name',$usernames)
            ->distinct()
            ->where('is_wait',1)
            ->pluck('add_wait_task_id')
            ->toArray();

        return BpmUserToDo::filter($parameters)
            ->whereIn('Userid',$usernames)
            ->distinct()
            ->whereNotIn('Taskid',$taskIdArray)
            ->select([
                'WF_OrUnid',
                'Subject',
                'WF_AddName_CN',
                'WF_DocCreated',
                'WF_ProcessName',
                'NodeName',
                'Nodeid'
            ])
            ->orderBy('StartTime','Desc')
            ->paginate(30)
            ->map(function ($item){
                return [
                    'id'        => $item->WF_OrUnid,
                    'subject'   => $item->Subject,
                    'title'     => $item->WF_ProcessName,
                    'date'      => date('Y-m-d',strtotime($item->WF_DocCreated)),
                    'username'  => $item->WF_AddName_CN,
                    'node_name' => $item->NodeName,
                    'node_id'   => $item->Nodeid
                ];
            })
            ->toArray();
    }

    /**
     * 所有服务单
     * @param string|null $username
     * @param array $parameters
     * @return array
     */
    public function getNeedDealAllServiceList(string $username = null,array $parameters = []) : array
    {
        $usernames = User::pluck('username')
            ->toArray();

        if (empty($usernames)){
            return [];
        }

        $taskIdArray = AssessmentUserAcceptance::whereIn('add_wait_name',$usernames)
            ->distinct()
            ->where('is_wait',1)
            ->pluck('add_wait_task_id')
            ->toArray();

        return BpmUserToDo::filter($parameters)
            ->whereIn('Userid',$usernames)
            ->distinct()
            ->whereNotIn('Taskid',$taskIdArray)
            ->select([
                'WF_OrUnid',
                'Subject',
                'WF_AddName_CN',
                'WF_DocCreated',
                'WF_ProcessName',
                'NodeName',
                'Nodeid'
            ])
            ->orderBy('StartTime','Desc')
            ->paginate(30)
            ->map(function ($item){
                return [
                    'id'        => $item->WF_OrUnid,
                    'subject'   => $item->Subject,
                    'title'     => $item->WF_ProcessName,
                    'date'      => date('Y-m-d',strtotime($item->WF_DocCreated)),
                    'username'  => $item->WF_AddName_CN,
                    'node_name' => $item->NodeName,
                    'node_id'   => $item->Nodeid
                ];
            })
            ->toArray();
    }

    /**
     * 将xml转换成array
     * @param string $xml
     * @return array
     */
    public function formatXml(string $xml) : array
    {
        $array = XmlToArray::convert($xml);

        $array = $array['WFItem'] ?? [];

        $data = [];

        foreach ($array as $value){
            if (isset($value['@attributes']['name']) && !empty($value['@attributes']['name'])) {
                $data[$value['@attributes']['name']] = $value['@content'] ?? null;
            }
        }

        return $data ?? [];
    }

    /**
     * 将array数据转换成xml的格式
     * @param array $array
     * @return string
     * @throws \DOMException
     */
    public function formatArray(array $array) : string
    {
        if (empty($array)) {
            return '';
        }

        $result = [
            'WFItem' => []
        ];

        foreach ($array as $key => $value) {
            if (empty($value)) {
                $result['WFItem'][] = [
                    '@attributes' => [
                        'name' => $key
                    ]
                ];
            } else {
                $result['WFItem'][] = [
                    '@attributes' => [
                        'name' => $key,
                    ],
                    '@cdata' => $value
                ];
            }
        }

        $xml = new ArrayToXml($result,'Items');

        return $xml->dropXmlDeclaration()->toXml();
    }

    /**
     * it服务单的详情信息
     * @param string $id
     * @return array
     */
    public function getReportDetails(string $id) : array
    {
        try{
            $currentRecord = BpmMaindata::where('WF_OrUnid',$id)
                ->select([
                    'Subject',
                    'XmlData',
                ])
                ->first();

            $xmlData = $currentRecord['XmlData'];

            if (empty($xmlData)) {
                $xmlData = BpmArchivedData::where('WF_OrUnid',$id)
                    ->value('XmlData');

                if (empty($xmlData)) {
                    return customer_return_success('success',[]);
                }
            }

            $data = $this->formatXml($xmlData);

            if (empty($data)) {
                return customer_return_success('success',[]);
            }

            $currentNodeId = BpmUserToDo::where('WF_OrUnid',$id)
                ->where('Userid',$this->getUsername())
                ->where('WF_Status','Current')
                ->value('Nodeid');

            $data = [
                'applicant' => [
                    'apply_date'       => (!isset($data['applyDate']) || empty($data['applyDate'])) ? '' : date('Y-m-d',strtotime( $data['applyDate'])),
                    'apply_username'   => $data['applyPerson'] ?? '',
                    'apply_department' => $data['applyDept_show'] ?? '',
                    'apply_phone'      => $data['applyPersonPhone'] ?? '',
                    'currUserNodeID'   => $currentNodeId ?? '',
                    'CustomNodeID'     => 'requirement_decompose' ?? '',
                    'ggtopl'           => (!isset($data['ggtopl']) || empty($data['ggtopl']) || $data['ggtopl'] == 'false' || $data['ggtopl'] == 'FALSE') ? 0 : 1,
                    'ggtofj'           => (!isset($data['ggtofj']) || empty($data['ggtofj']) || $data['ggtofj'] == 'false' || $data['ggtofj'] == 'FALSE') ? 0 : 1,
                    'if_one_system_manager' => (!isset($data['if_one_system_manager']) || empty($data['if_one_system_manager']) || $data['if_one_system_manager'] == 'false' || $data['if_one_system_manager'] == 'FALSE') ? 0 : 1,
                    'pzsx'             => (!isset($data['pzsx']) || empty($data['pzsx']) || $data['pzsx'] == 'false' || $data['pzsx'] == 'FALSE') ? 0 : 1
                ],
                'details' => [
                    'apply' => [
                        'department' => $data['headDept_show'] ?? '',
                        'leader'     => $data['headPerson_show'] ?? '',
                    ],
                    'basic' => [
                        'subject'       => isset($data['Subject_show']) ? $data['Subject_show'] : $currentRecord['Subject'],
                        'number'        => $data['reqNum'] ?? '',
                        'one_category'  => $data['reqOneType'] ??  '',
                        'two_category'  => $data['reqTwoType'] ?? '',
                        'status'        => $data['statusName'] ?? '',
                        'hope_date'     => $data['hopeDate'] ?? '',
                        'urgency'       => $data['keyMark'] ?? '',
                        'debug_date'    => $data['integrationTestTime'] ?? '',
                        'start_date'    => $data['startUp'] ?? '',
                        'complete_date' => $data['planTime'] ?? '',
//                        'background'    => strip_tags($data['reqGround'] ?? ''),
                        'background'    => strip_tags( htmlspecialchars_decode($data['reqGround'])) ?? '',  //隐藏前端字段
                        'describe'      => $data['reqDesc'] ?? '',
                        'year_plan'     => (!isset($data['radio17']) || empty($data['radio17'])) ? false : $data['radio17'] != 'no',
                        'oa_status'     => $data['oaStatus'] ?? ''
                    ]
                ]
            ];

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('it 服务单详情：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 审批记录展示
     * @param string $id
     * @return array
     */
    public function getApprovalRecord(string $id): array
    {
        try{
            $xmlData = BpmMaindata::where('WF_OrUnid',$id)
                ->value('XmlData');

            if (empty($xmlData)) {
                $xmlData = BpmArchivedData::where('WF_OrUnid',$id)
                    ->value('XmlData');

                if (empty($xmlData)) {
                    return customer_return_success('success',[]);
                }
            }

            $data = $this->formatXml($xmlData);

            if (empty($data)) {
                return customer_return_success('success',[]);
            }

            $data = [
                'applicant' => [
                    'apply_date'       => (!isset($data['applyDate']) || empty($data['applyDate'])) ? '' : date('Y-m-d',strtotime( $data['applyDate'])),
                    'apply_username'   => $data['applyPerson'] ?? '',
                    'apply_department' => $data['applyDept_show'] ?? '',
                    'apply_phone'      => $data['applyPersonPhone'] ?? '',
                ]
            ];

            $reports = [];

            $current = BpmInsUserList::where('DocUnid',$id)
                ->where('Status','Current')
                ->select([
                    'Userid',
                    'startTime',
                    'FirstReadTime',
                    'ExceedTime',
                    'LimitTime'
                ])
                ->first();

            if (!is_null($current)){
                $current = $current->toArray();

                $userId = $current['Userid'];

                if (!empty($userId)) {
                    $userName = BpmOrgUserList::where('userid',$userId)
                        ->value('CnName');

                    $deptName = BpmOrgDeptList::Join('BPM_OrgUserDeptMap',function ($join){
                        return $join->on('BPM_OrgDeptList.Folderid','=','BPM_OrgUserDeptMap.Folderid');
                    })
                        ->where('BPM_OrgUserDeptMap.Userid',$userId)
                        ->where('BPM_OrgUserDeptMap.CurrentFlag',1)
                        ->where('BPM_OrgUserDeptMap.OrgClass',1)
                        ->where('BPM_OrgDeptList.OrgClass',1)
                        ->value('BPM_OrgDeptList.FolderName');

                    $reports[] = [
                        'node_name'       => '',
                        'end_date'        => '',
                        'username'        => $userName,
                        'department_name' => $deptName,
                        'remark_type'     => '',
                        'remark'          => $current['FirstReadTime'] ? '已阅（'.$current['FirstReadTime'].'）' : ''
                    ];
                }
            }

            $list = BpmInsremarklist::where('DocUnid',$id)
                ->where('IsReadFlag',0)
                ->orderBy('EndTime','Desc')
                ->orderBy('StartTime','Desc')
                ->get()
                ->map(function ($value){
                    return [
                        'node_name'       => $value->NodeName,
                        'end_date'        => $value->EndTime,
                        'username'        => $value->UserName,
                        'department_name' => $value->DeptName,
                        'remark_type'     => $value->RemarkType,
                        'remark'          => $value->Remark
                    ];
                })
                ->toArray();

            $data['list'] = array_merge($reports,$list);

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('it 服务单审核记录异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 获取到oa记录展示
     * @param string $id
     * @return mixed
     */
    public function getOaRecord(string $id) : array
    {
        try{
            $xmlData = BpmMaindata::where('WF_OrUnid',$id)
                ->value('XmlData');

            if (empty($xmlData)) {
                $xmlData = BpmArchivedData::where('WF_OrUnid',$id)
                    ->value('XmlData');

                if (empty($xmlData)) {
                    return customer_return_success('success',[]);
                }
            }

            $data = $this->formatXml($xmlData);

            if (empty($data)) {
                return customer_return_success('success',[]);
            }

            $data = [
                'applicant' => [
                    'apply_date'       => (!isset($data['applyDate']) || empty($data['applyDate'])) ? '' : date('Y-m-d',strtotime( $data['applyDate'])),
                    'apply_username'   => $data['applyPerson'] ?? '',
                    'apply_department' => $data['applyDept_show'] ?? '',
                    'apply_phone'      => $data['applyPersonPhone'] ?? '',
                ]
            ];

            $list = AssessmentOaDocking::where('instanceId',$id)
                ->orderBy('ADDDATE','desc')
                ->get()
                ->map(function($value){
                    return [
                        'date'    => date('Y-m-d H:i',strtotime($value->adddate)),
                        'message' => $value->msg,
                        'status'  => $value->status == 'true'
                    ];
                })
                ->toArray();

            $data['list'] = $list;

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('it 服务单 oa记录异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * @param string $id
     * 获取到需求分解单列表信息
     * @return array
     */
    public function getTaskDecompose(string $id) : array
    {
        try{
            $xmlData = BpmMaindata::where('WF_OrUnid',$id)
                ->value('XmlData');

            if (empty($xmlData)) {
                $xmlData = BpmArchivedData::where('WF_OrUnid',$id)
                    ->value('XmlData');

                if (empty($xmlData)) {
                    return customer_return_success('success',[]);
                }
            }

            $data = $this->formatXml($xmlData);

            if (empty($data)) {
                return customer_return_success('success',[]);
            }

            //判断是否存在牵头分解单
            $leader = [];

            if (isset($data['architectrueReview']) && !empty($data['architectrueReview'])) {
                $framework = trim($data['architectrueReview'],',');

                if (empty($framework)) {
                    $framework = [];
                } else {
                    $framework = explode(",",$framework);
                }
            }

//            if (isset($data['leadTeam']) && !empty($data['leadTeam'])) {
                $leader = [
                    'involve_system_name' => $data['involvedSystem'] ?? '',
                    'leader_team_name'    => $data['leadTeam'] ?? '',
                    'leader_name'         => $data['leader'] ?? '',
                    'project_leader_name' => $data['projectLeader'] ?? '',
                    'framework'           => $framework ?? []
                ];

                if (isset($data['leadTeam']) && !empty($data['leadTeam'])) {
                    $leadTeam = Unit::where('id',$data['leadTeam'])
                        ->where('is_deleted',0)
                        ->value('name');
                }

                if (isset($data['leader']) && !empty($data['leader'])) {
                    $user = User::where('username',$data['leader'])
                        ->first();

                    if (!is_null($user)){
                        $leaderName = $user->person->name ?? '';
                    }
                }

                if (isset($data['projectLeader']) && !empty($data['projectLeader'])) {
                    $projectLeader = Person::where('id',$data['projectLeader'])
                        ->where('is_deleted',0)
                        ->value('name');
                }

                $leader = array_merge($leader,[
                    'leader_team_name'    =>  $leadTeam ?? '',
                    'leader_name'         =>  $leaderName ?? '',
                    'project_leader_name' =>  $projectLeader ?? ''
                ]);
//            }

            $leader = array_merge($leader,[
                'opinion'    =>  $data['archOpinions'] ?? '',
            ]);

            $list = AssessmentReqDevSpilt::from('assessment_req_dev_spilt as ads')
                ->distinct()
                ->leftJoin('bpm_orguserlist as bo',function ($join){
                    return $join->on('bo.pmsUserId','=','ads.req_name_id')
                        ->orOn('bo.pmsUserId','=','ads.dev_name_id');
                })
                ->where('ads.instanceId',$id)
                ->where(function ($query){
                    return $query->where('ads.spilt_return',1)
                        ->orWhere('ads.spilt_return',0);
                })
                ->select([
                    'ads.WF_OrUnid',
                    'ads.plate_name',
                    'ads.invovle_sys',
                    'ads.dev_name'
                ])
                ->orderBy('ord_id')
                ->get()
                ->map(function ($item){
                    return [
                        'id'          => $item->WF_OrUnid,
                        'plate_name'  => $item->plate_name,
                        'system_name' => $item->invovle_sys,
                        'leader'      => $item->dev_name
                    ];
                })
                ->toArray();

            if (empty($leader)) {
                $leader = null;
            }

            return customer_return_success('success',compact('leader','list'));
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单需求分解单列表异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 需求分解单牵头展示
     * @param string $id
     * @return array
     */
    public function getTaskDecomposeLeaderDetails(string $id) : array
    {
        try{
            $data = AssessmentReqDevSpilt::from('assessment_req_dev_spilt as ads')
                ->distinct()
                ->leftJoin('bpm_orguserlist as bo',function ($join){
                    return $join->on('bo.pmsUserId','=','ads.req_name_id')
                        ->orOn('bo.pmsUserId','=','ads.dev_name_id');
                })
                ->where('ads.instanceId',$id)
                ->where(function ($query){
                    return $query->where('ads.spilt_return',1)
                        ->orWhere('ads.spilt_return',0);
                })
                ->select([
                    'ads.dev_office_id',
                    'ads.invovle_sys',
                    'ads.leader_id',
                ])
                ->orderBy('ord_id')
                ->first();

            if (is_null($data)) {
                return customer_return_success('success',[]);
            }

            //获取到团队长的姓名
            if (!empty($data->leader_id)) {
                $user = User::where('username',$data->leader_id)
                    ->first();

                if (!is_null($user)){
                    $leaderName = $user->person->name ?? '';
                }
            }

            //获取到牵头团队
            if (!empty($data->dev_office_id)){
                $leaderUnitName = Unit::where('id',$data->dev_office_id)
                    ->value('name');
            }

            $details = [
                'leader_name'      => $leaderName ?? '',
                'leader_unit_name' => $leaderUnitName ?? '',
                'system_name'      => $data->invovle_sys ?? '',
                'framework'        => '三重一大'
            ];

            return customer_return_success('success',$details);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单需求分解 牵头展示异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 搜索到分解单
     * @param string $search
     * @return array|mixed
     */
    public function searchTask(string $search): array
    {
        try{
            if (empty($search)) {
                return customer_return_success('success',[]);
            }

            $data = BpmFormatdoc::from('format_doc as p')
                ->leftJoin('s_system_formatdoc_standard_table_3 as sfst',function ($join){
                    return $join->on('p.standard_column_3','=','sfst.id');
                })
                ->leftJoin('plate_unit as pu',function ($join){
                    return $join->on('sfst.id','=','pu.plate_id');
                })
                ->leftJoin('unit as u',function ($join){
                    return $join->on('pu.unit_id','=','u.id');
                })
                ->where('p.is_deleted',0)
                ->where('p.standard_column_5','<>',4)
                ->whereNotNull('p.standard_column_3')
                ->where('p.NAME','like','%'.$search.'%')
                ->select(DB::raw('CONCAT(\'[\',GROUP_CONCAT( DISTINCT CONCAT (\'{"uid":"\',p.uid,\'","name":"\',p.NAME,\'","plateId":"\',sfst.id,\'","plateName":"\',sfst.NAME,\'","unitId":"\',u.id,\'","unitName":"\',u.NAME,\'"}\')),\']\') as result'))
                ->value('result');

            if (empty($data)){
                return customer_return_success('success',[]);
            }

            $data= json_decode($data,true);

            if (!empty($data)) {
                foreach($data as $key => $value){
                    //获取rep
                    $rep = RSystemPersonRole::where('doc_uid',$value['uid'])
                        ->where(function($query){
                            return $query->where('systemrole',3)
                                ->orwhere('systemrole',4);
                        })
                        ->pluck('user_id')
                        ->toArray();

                    //获取dev
                    $dev = RSystemPersonRole::where('doc_uid',$value['uid'])
                        ->where(function($query){
                            return $query->where('systemrole',1)
                                ->orwhere('systemrole',2);
                        })
                        ->pluck('user_id')
                        ->toArray();

                    $devData = BpmOrgUserList::whereIn('pmsUserId',$dev)
                        ->select([
                            'pmsUserId',
                            'CnName'
                        ])
                        ->get()
                        ->map(function($value){
                            return [
                                'id'   => $value['pmsUserId'],
                                'name' => $value['CnName']
                            ];
                        })
                        ->toArray();

                    $repData = BpmOrgUserList::whereIn('pmsUserId',$rep)
                        ->select([
                            'pmsUserId',
                            'CnName'
                        ])
                        ->get()
                        ->map(function($value){
                            return [
                                'id'   => $value['pmsUserId'],
                                'name' => $value['CnName']
                            ];
                        })
                        ->toArray();

                    $data[$key]['reqData'] = $repData;
                    $data[$key]['devData'] = $devData;
                }

                //格式化数据
                $data = array_map(function ($item){
                    return [
                        'involve_system_id'   => $item['uid'] ?? '',
                        'involve_system_name' => $item['name'] ?? '',
                        'plate_id'            => $item['plateId'] ?? '',
                        'plate_name'          => $item['plateName'] ?? '',
                        'unit_id'             => $item['unitId'] ?? '',
                        'unit_name'           => $item['unitName'] ?? '',
                        'request_data'        => $item['reqData'] ?? [],
                        'develop_data'        => $item['devData'] ?? []
                    ];
                },$data);

                return customer_return_success('success',$data);
            } else {
                return customer_return_success('success',[]);
            }
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 模糊查询异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 需求分解单详情
     * @param string $id
     * @return array
     */
    public function getTaskDecomposeDetails(string $id) : array
    {
        try{
            $data = AssessmentReqDevSpilt::where('WF_OrUnid',$id)
                ->first();

            if (is_null($data)) {
                return customer_return_error('id 不存在',[]);
            }

            if (!empty($data->dev_data)){
                $developData = json_decode($data->dev_data,true);
            }

            if (!empty($data->req_data)){
                $requestData = json_decode($data->req_data,true);
            }

            $details = [
                'unit_id'             => $data->dev_office_id,
                'develop_data'        => $developData ?? [],
                'involve_system_name' => $data->invovle_sys,
                'involve_system_id'   => $data->invovle_sys_id,
                'develop_name_id'     => $data->dev_name_id,
                'plate_name'          => $data->plate_name,
                'develop_name'        => $data->dev_name,
                'unit_name'           => $data->dev_office,
                'request_data'        => $requestData ?? [],
                'id'                  => $data->WF_OrUnid,
                'plate_id'            => $data->plate_id
            ];

            return customer_return_success('success',$details);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 需求分解单详情异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 创建需求分解单
     * @param array $parameters
     * @return array
     */
    public function taskDecomposeCreate(array $parameters) : array
    {
        try{
            $data = [
                'create_name'    => $this->getUsername(),
                'dev_office_id'  => $parameters['unit_id'],
                'dev_data'       => $parameters['develop_data'],
                'invovle_sys'    => $parameters['involve_system_name'],
                'invovle_sys_id' => $parameters['involve_system_id'],
                'dev_name_id'    => $parameters['develop_name_id'],
                'plate_name'     => $parameters['plate_name'],
                'dev_name'       => $parameters['develop_name'],
                'dev_office'     => $parameters['unit_name'],
                'instanceId'     => $parameters['server_id'],
                'req_data'       => $parameters['request_data'],
                'WF_OrUnid'      => Str::uuid()->toString(),
                'plate_id'       => $parameters['plate_id'],
            ];

            //根据dev的name_id 获取到 username
            $leaderId = Person::from('pms.person as p')
                ->leftJoin('user as u',function ($join){
                    return $join->on('p.id','=','u.id');
                })
                ->leftJoin('r_person_post as rpp',function ($join){
                    return $join->on('rpp.person_id','=','p.id');
                })
                ->leftJoin('post as po',function ($join){
                    return $join->on('po.unit_id','=','p.unit_id');
                })
                ->leftJoin('person as p1',function ($join){
                    return $join->on('p1.unit_id','=','po.unit_id');
                })
                ->whereRaw('rpp.post_id = po.id')
                ->where('p1.id',$parameters['develop_name_id'])
                ->where('po.is_leader',1)
                ->value('u.username');


            $data['leader_id'] = $leaderId;

            AssessmentReqDevSpilt::insert($data);

            return customer_return_success('创建成功',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单创建需需求分解单异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * 修改需求分解单
     * @param array $parameters
     * @return array
     */
    public function taskDecomposeUpdate(array $parameters) : array
    {
        try{
            $data = [
                'dev_office_id'  => $parameters['unit_id'],
                'dev_data'       => $parameters['develop_data'],
                'invovle_sys'    => $parameters['involve_system_name'],
                'invovle_sys_id' => $parameters['involve_system_id'],
                'dev_name_id'    => $parameters['develop_name_id'],
                'plate_name'     => $parameters['plate_name'],
                'dev_name'       => $parameters['develop_name'],
                'dev_office'     => $parameters['unit_name'],
                'req_data'       => $parameters['request_data'],
                'plate_id'       => $parameters['plate_id'],
            ];

            //根据dev的name_id 获取到 username
            $leaderId = Person::from('pms.person as p')
                ->leftJoin('user as u',function ($join){
                    return $join->on('p.id','=','u.id');
                })
                ->leftJoin('r_person_post as rpp',function ($join){
                    return $join->on('rpp.person_id','=','p.id');
                })
                ->leftJoin('post as po',function ($join){
                    return $join->on('po.unit_id','=','p.unit_id');
                })
                ->leftJoin('person as p1',function ($join){
                    return $join->on('p1.unit_id','=','po.unit_id');
                })
                ->whereRaw('rpp.post_id = po.id')
                ->where('p1.id',$parameters['develop_name_id'])
                ->where('po.is_leader',1)
                ->value('u.username');

            $data['leader_id'] = $leaderId;

            AssessmentReqDevSpilt::where('WF_OrUnid',$parameters['decompose_id'])
                ->update($data);

            return customer_return_success('success',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单编辑需求分解单异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * 删除需求分解单
     * @param array $parameters
     * @return array
     */
    public function taskDecomposeDestroy(array $parameters) : array
    {
        try{
            $count = AssessmentReqDevSpilt::from('assessment_req_dev_spilt as ads')
                ->distinct()
                ->leftJoin('bpm_orguserlist as bo',function ($join){
                    return $join->on('bo.pmsUserId','=','ads.req_name_id')
                        ->orOn('bo.pmsUserId','=','ads.dev_name_id');
                })
                ->where('ads.instanceId',$parameters['server_id'])
                ->where(function ($query){
                    return $query->where('ads.spilt_return',1)
                        ->orWhere('ads.spilt_return',0);
                })
                ->select([
                    'ads.WF_OrUnid',
                    'ads.plate_name',
                    'ads.invovle_sys',
                    'ads.dev_name'
                ])
                ->count();

            if ($count == 1) {
                return customer_return_error('板块系统不能为空',[]);
            }

            AssessmentReqDevSpilt::where('WF_OrUnid',$parameters['task_id'])
                ->delete();

            return customer_return_success('success');
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 删除需求分解单异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * 设置需求分解单 牵头单位列表
     * @param string $id
     * @return array
     */
    public function getTaskDecomposeLeaderList(string $id) : array
    {
        try {
            $data =  AssessmentReqDevSpilt::from('assessment_req_dev_spilt as ads')
                ->distinct()
                ->leftJoin('bpm_orguserlist as bo',function ($join){
                    return $join->on('bo.pmsUserId','=','ads.req_name_id')
                        ->orOn('bo.pmsUserId','=','ads.dev_name_id');
                })
                ->where('ads.instanceId',$id)
                ->where(function ($query){
                    return $query->where('ads.spilt_return',1)
                        ->orWhere('ads.spilt_return',0);
                })
                ->select([
                    'ads.WF_OrUnid',
                    'ads.plate_name',
                    'ads.invovle_sys',
                    'ads.dev_name'
                ])
                ->orderBy('ord_id')
                ->get()
                ->map(function ($item){
                    return [
                        'id'          => $item->WF_OrUnid,
                        'plate_name'  => $item->plate_name,
                        'system_name' => $item->invovle_sys,
                        'leader'      => $item->dev_name
                    ];
                })
                ->toArray();

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 需求分解单 设置牵头单位列表异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * 设置需求分解单 牵头单位
     * @param array $parameters
     * @return array
     */
    public function getTaskDecomposeLeader(array $parameters): array
    {
        try {
            $leader = AssessmentReqDevSpilt::where('WF_OrUnid',$parameters['task_id'])
                ->select([
                    'dev_office',
                    'dev_office_id',
                    'invovle_sys',
                    'leader_id'
                ])
                ->first();

            if (is_null($leader)){
                return customer_return_error('task_id 异常');
            }

            $leader = $leader->toArray();
            if (isset($leader['leader_id']) && !empty($leader['leader_id'])) {
                $user = User::where('username',$leader['leader_id'])
                    ->first();

                if (!is_null($user)){
                    $leaderName = $user->person->name ?? '';
                }
            }
            $xmlData = BpmMaindata::where('WF_OrUnid',$parameters['server_id'])
                ->value('XmlData');

            if (empty($xmlData)) {
                return customer_return_error('server_id 异常');
            }

            $data = $this->formatXml($xmlData);

            //设置牵头单位信息
            $data['leadTeam']       = $leader['dev_office_id'];
            $data['leadTeam_show']  = $leader['dev_office'];
            $data['involvedSystem'] = $leader['invovle_sys'];
            $data['leader']         = $leader['leader_id'];
            $data['leader_show']    = $leaderName ?? '';

            $xml = $this->formatArray($data);

            BpmMaindata::where('WF_OrUnid',$parameters['server_id'])
                ->update([
                    'XmlData' => $xml
                ]);

            return customer_return_success('success');
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 需求分解单 设置牵头单位异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * 更新需求分解单 牵头单位
     * @param array $parameters
     * @return array
     */
    public function updateTaskDecomposeLeader(array $parameters): array
    {
        try {
            $xmlData = BpmMaindata::where('WF_OrUnid',$parameters['server_id'])
                ->value('XmlData');

            if (empty($xmlData)) {
                return customer_return_error('server_id 异常');
            }

            $data = $this->formatXml($xmlData);

            //设置牵头单位信息
            $data['leadTeam']       = $parameters['leadTeamID'];
            $data['leadTeam_show']  = $parameters['leadTeamName'];
            $data['involvedSystem'] = '';
            $data['leader']         = $parameters['leadUserName'];
            $data['leader_show']    = $parameters['leaderName'] ?? '';

            $xml = $this->formatArray($data);

            BpmMaindata::where('WF_OrUnid',$parameters['server_id'])
                ->update([
                    'XmlData' => $xml
                ]);

            return customer_return_success('success');
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 需求分解单 更新牵头单位异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * 获取可选的牵头团队列表
     * @return array
     */
    public function getLeadTeamList():array {
        try {
            $data =  Unit::where('unit.parent_id',375)
                ->where('unit.is_deleted',0)
                ->leftJoin('pms.person as p', 'p.unit_id', '=', 'unit.id')
                ->leftJoin('pms.r_person_post as rpp', 'p.id', '=', 'rpp.person_id')
                ->leftJoin('pms.user as us', 'us.person_id', '=', 'p.id')
                ->where('rpp.post_id' ,'!=', 9)
                ->where('p.is_deleted',0)
                ->select([
                    'unit.id',
                    'unit.name',
                    'us.username',
                    DB::raw('p.name as leader_name')

                ])
                ->orderBy('unit.ord')
                ->get()
                ->map(function ($item){
                    return [
                        'leadTeamID'    => $item->id,
                        'leadTeamName'  => $item->name,
                        'leadUserName'  => $item->username,
                        'leaderName'    => $item->leader_name,
                    ];
                })
                ->toArray();

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 需求分解单 获取可选牵头单位列表异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }
    /**
     * 牵头单位架构审核
     * @return mixed
     */
    public function getTaskDecomposeLeaderFramework() : array
    {
        $data = [
            [
                'id'    => 'architectrueReview1',
                'value' => '是否新建系统'
            ],
            [
                'id'    => 'architectrueReview2',
                'value' => '是否三重一大'
            ]
        ];

        return customer_return_success('success',$data);
    }

    /**
     * 设置牵头单位 设置架构审核
     * @param array $parameters
     * @return array
     */
    public function taskDecomposeLeaderUpdateFramework(array $parameters) : array
    {
        try {
            $xmlData = BpmMaindata::where('WF_OrUnid',$parameters['server_id'])
                ->value('XmlData');

            if (empty($xmlData)) {
                return customer_return_error('server_id 异常');
            }

            $data = $this->formatXml($xmlData);

            if (isset($parameters['framework']) && !empty($parameters['framework'])){
                $data['architectrueReview'] = implode(',',$parameters['framework']);
            } else {
                $data['architectrueReview'] = ',';
            }

            $xml = $this->formatArray($data);

            BpmMaindata::where('WF_OrUnid',$parameters['server_id'])
                ->update([
                    'XmlData' => $xml
                ]);

            return customer_return_success('success',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 需求分解单 设置牵头单位  设置架构审核 异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * 将需求分解单设置为牵头单位
     * @param string $id
     * @return array
     */
    public function taskDecomposeLeader(string $id) : array
    {
        try{
            $data = AssessmentReqDevSpilt::where('WF_OrUnid',$id)
                ->select([
                    'dev_office_id',
                    'invovle_sys',
                    'leader_id'
                ])
                ->first();

            if (is_null($data)) {
                return customer_return_error('需求分解单不存在');
            }

            $data = $data->toArray();

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 需求分解单设置牵头单位异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * @note 工作量评估数据展示
     * @param string $id
     * @return array
     */
    public function getWorkAssess(string $id): array
    {
        try{
            $xmlData = BpmMaindata::where('WF_OrUnid',$id)
                ->value('XmlData');

            if (empty($xmlData)) {
                $xmlData = BpmArchivedData::where('WF_OrUnid',$id)
                    ->value('XmlData');

                if (empty($xmlData)) {
                    return customer_return_success('success',[]);
                }
            }

            $data = $this->formatXml($xmlData);

            if (empty($data)) {
                return customer_return_success('success',[]);
            }

            $data = [
                'applicant' => [
                    'apply_date'       => (!isset($data['applyDate']) || empty($data['applyDate'])) ? '' : date('Y-m-d',strtotime( $data['applyDate'])),
                    'apply_username'   => $data['applyPerson'] ?? '',
                    'apply_department' => $data['applyDept_show'] ?? '',
                    'apply_phone'      => $data['applyPersonPhone'] ?? '',
                ]
            ];

            $assess = AssessmentReqDevSpilt::from('assessment_req_dev_spilt as ads')
                ->leftJoin('bpm_orguserlist as bo',function ($join){
                    return $join->on('bo.pmsUserId','=','ads.dev_name_id')
                        ->orOn('bo.pmsUserId', '=','ads.dev_name_id');
                })
                ->where('ads.instanceId',$id)
                ->select([
                    'ads.WF_OrUnid',
                    'ads.plate_name',
                    'ads.invovle_sys',
                    'ads.dev_name',
                    'ads.dev_name_id', // 系统负责人ID
                    'ads.it',
                    DB::raw('case when ads.source_type_id = 2 then ads.it else 0 end it2'),
                    'ads.cycle' // 实施周期，用于判断内容是否已填
                ])
                ->orderBy('ord_id','asc')
                ->get()
                ->map(function ($value){
                    return [
                        'id'          => $value->WF_OrUnid,
                        'plate_name'  => $value->plate_name,
                        'system_name' => $value->invovle_sys,
                        'leader_name' => $value->dev_name,
                        'leader_id'   => $value->dev_name_id,
                        'assessed'    => strlen($value->cycle)>0 ? 1 : 0,  // 工作量评估详情是否已填，1已填，0未填
                        'is_mine'     => $value->dev_name_id == auth('api')->user()->id ? 1 : 0,  // 当前登陆人是否为系统负责人，1是0否
                        'it_amount'   => floatval($value->it) ?: '0.00',
                        'it2'         => floatval($value->it2) ?: '0.00'
                    ];
                });

            //it金额
            $itTotalAmount = $assess->sum('it_amount') . '万元';

            //立项金额
//            $projectTotalAmount = $assess->sum('it_amount') . '万元';

            $projectTotalAmount = ($assess->sum('it2')
                + ($data['text59'] ?? 0)
                + ($data['text63'] ?? 0)
                + ($data['text66'] ?? 0)
                + ($data['text67'] ?? 0)
                + ($data['text69'] ?? 0)
                + ($data['text700'] ?? 0)). '万元';

            $assess = $assess->map(function ($value){
                unset($value['it_amount']);

                return $value;
            })->toArray();

            $data['assess'] = $assess;

            $data['amount'] = [
                'estimate_it_amount'   => $itTotalAmount,
                'project_total_amount' => $projectTotalAmount,
            ];

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 工作量评估数据展示异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 获取到工作量评估详情
     * @param string $id
     * @return array
     */
    public function getWorkAssessDetails(string $id) : array
    {
        try{
            $data = AssessmentReqDevSpilt::where('WF_OrUnid',$id)
                ->select([
                    'dev_name',
                    'dev_name_id',  // 系统负责人ID
                    'plate_name',
                    'invovle_sys',
                    'invovle_sys_id',
                    'implement_common',
                    'implement_common_id',
                    'function_name',
                    'source_type',
                    'manufacturer',
                    'price',
                    'workflow',
                    'it',
                    'project_num',
                    'cycle',
                    'start_up',
                    'check_time',
                    'is_big_file',
                    'is_net',
                    'is_netted',
                    'is_other',
                    'data_save_req',
                    'reliable_req',
                    'WF_OrUnid',
                    'source_type_id',
                    'manufacturer_id'
                ])
                ->first();

            if (is_null($data)) {
                return customer_return_error('id 异常，数据不存在');
            }

            $details = [
                'id'                   => $data->WF_OrUnid,
                'leader_name'          => $data->dev_name,
                'plate_name'           => $data->plate_name,
                'system_name'          => $data->invovle_sys,
                'system_id'            => $data->invovle_sys_id,
                'implement_content'    => $data->implement_common,
                'implement_comment_id' => $data->implement_common_id,
                'function_name'        => $data->function_name,
                'source_type'          => $data->source_type,
                'source_type_id'       => $data->source_type_id,
                'manufacturer'         => $data->manufacturer,
                'manufacturer_id'      => $data->manufacturer_id,
                'price'                => $data->price,
                'workflow'             => $data->workflow,
                'estimate_it_amount'   => $data->it,
                'project_number'       => $data->project_num,
                'cycle'                => $data->cycle,
                'start_date'           => $data->start_up,
                'check_date'           => $data->check_time,
                'is_big_file'          => $data->is_big_file != '否',
                'is_net'               => $data->is_net != '否',
                'is_netted'            => $data->is_netted != '否',
                'is_other'             => $data->is_other != '否',
                'data_save_request'    => $data->data_save_req,
                'reliable_request'     => $data->reliable_req,
                'is_mine'              => $data->dev_name_id == auth('api')->user()->id ? 1 : 0,  // 当前登陆人是否为系统负责人，1是0否
            ];

            return customer_return_success('success',$details);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 工作量评估详情异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 创建人月信息
     * @param array $parameters
     * @return array
     */
    public function createEstimateWorking(array $parameters)  : array
    {
        try{
            if (isset($parameters['estimate_id'])) {
                $data = AssReqFunctionList::where('WF_OrUnid',$parameters['estimate_id'])
                    ->first();

                if (is_null($data)) {
                    return customer_return_error('estimate_id 异常,保存失败');
                }

                AssReqFunctionList::where('WF_OrUnid',$parameters['estimate_id'])
                    ->update([
                        'req__analyze'        => $parameters['analyze'],
                        'sys_config'          => $parameters['config'],
                        'sys_design'          => $parameters['design'],
                        'sys_dev'             => $parameters['developer'],
                        'sys_test'            => $parameters['test'],
                        'project_manage'      => $parameters['project'],
                        'split_desc'          => $parameters['describe'],
                    ]);
            } else {
                AssReqFunctionList::insert([
                    'function_name'       => $parameters['function_name'],
                    'req__analyze'        => $parameters['analyze'],
                    'sys_config'          => $parameters['config'],
                    'sys_design'          => $parameters['design'],
                    'sys_dev'             => $parameters['developer'],
                    'sys_test'            => $parameters['test'],
                    'project_manage'      => $parameters['project'],
                    'create_name'         => auth('api')->user()->username,
                    'req_dev_spilt_id'    => $parameters['assess_id'],
                    'WF_OrUnid'           => Str::uuid()->toString(),
                    'instanceId'          => $parameters['server_id'],
                    'implement_common_id' => $parameters['implement_content_id'],
                    'invovle_sys'         => $parameters['system_id'],
                    'split_desc'          => $parameters['describe'],
                ]);
            }

            $totalEstimate = $parameters['analyze']
                + $parameters['config']
                + $parameters['design']
                + $parameters['developer']
                + $parameters['test']
                + $parameters['project'];

            $workflow = number_format($totalEstimate/22,2);

            $itAmount = number_format($totalEstimate * $parameters['price'],2);

            $data = [
                'workflow'           => $workflow,
                'estimate_it_amount' => $itAmount
            ];

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 保存人月异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * 获取到预计人月到数据
     * @param array $parameters
     * @return array
     */
    public function getEstimateWorking(array $parameters) : array
    {
        try{
            $data = AssReqFunctionList::where('instanceId',$parameters['server_id'])
                ->where('implement_common_id',$parameters['implement_content_id'])
                ->where('invovle_sys',$parameters['system_id'])
                ->where('function_name',$parameters['function_name'])
                ->select([
                    'WF_OrUnid',
                    'split_desc',
                    'req__analyze',
                    'sys_config',
                    'sys_design',
                    'sys_dev',
                    'sys_test',
                    'project_manage'
                ])
                ->get()
                ->map(function ($value){
                    return [
                        'id'        => $value->WF_OrUnid,
                        'describe'  => $value->split_desc,
                        'analyze'   => strlen($value->req__analyze) > 0 ? $value->req__analyze : "0.00",
                        'config'    => strlen($value->sys_config)  > 0 ? $value->sys_config : "0.00",
                        'design'    => strlen($value->sys_design)  > 0 ? $value->sys_design : "0.00",
                        'developer' => strlen($value->sys_dev)  > 0 ? $value->sys_dev : "0.00",
                        'test'      => strlen($value->sys_test)  > 0 ? $value->sys_test : "0.00",
                        'project'   => strlen($value->project_manage)  > 0 ? $value->project_manage : "0.00"
                    ];
                })
                ->toArray();

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 工作量评估需求人月详情异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 工作量评估资源类型条件查询
     * @return array
     */
    public function getWorkAssessConditionResourcesImplementation() : array
    {
        try{
            $data = SOriginalFormatModuleContent::select([
                'id',
                'name'
            ])
                ->get()
                ->map(function ($value){
                    return [
                        'id'    => $value->id,
                        'value' => $value->name
                    ];
                })
                ->toArray();

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 工作量评估实施内容条件查询异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 工作量评估资源类型条件查询
     * @return mixed
     */
    public function getWorkAssessConditionResourcesResources() : array
    {
        $data = [
            [
                'id'    => 1,
                'value' => '保障人力型',
            ],
            [
                'id'    => 2,
                'value' => '项目交付型'
            ],
            [
                'id'    => 3,
                'value' => '自主研发型'
            ],
        ];

        return customer_return_success('success',$data);
    }

    /**
     * 工作量评估厂商条件查询
     * @param array $parameters
     * @return array
     */
    public function getWorkAssessConditionManufacturer(array $parameters) : array
    {
        try{
            if(isset($parameters['type_id']) && !empty($parameters['type_id']) && $parameters['type_id'] == 3) {
//                $data = Unit::where('name','信息技术部')
//                    ->where('id', 375)
//                    ->select([
//                        'id',
//                        'name'
//                    ])
//                    ->get()
//                    ->map(function ($value){
//                        return [
//                            'id'    => $value->id,
//                            'value' => $value->name
//                        ];
//                    })
//                    ->toArray();
                $data[] = [
                    'id'    => 375,
                    'value' => '信息技术部'
                ];
//                $data = $data
//                    ? current($data)
//                    : $data;
            } else {
                $data = [];

                $units = FormatDoc::where('uid',$parameters['system_id'])
                    ->pluck('unit_Multiple_1')
                    ->toArray();

                foreach ($units as $id) {
                    $value = BpmOrgDeptList::where('unitId',$id)
                        ->value('FolderName');

                    if (!empty($value)) {
                        $data[] = [
                            'id'    => $id,
                            'value' => $value
                        ];
                    }
                }

                $id = Unit::where('name','待定')
                    ->where('category_id',3)
                    ->value('id');

                $data[] = [
                    'id'    => (int) $id,
                    'value' => '待定'
                ];
            }

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 工作量评估实施内容条件查询异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 工作量评估 编辑
     * @param array $parameters
     * @return array
     */
    public function updateWorkAssess(array $parameters) : array
    {
        try{
            $data = [
                'implement_common'    => $parameters['implement_content'],
                'implement_common_id' => $parameters['implement_content_id'],
                'function_name'       => $parameters['function_name'],
                'source_type'         => $parameters['source_type'],
                'source_type_id'      => $parameters['source_type_id'],
                'manufacturer'        => $parameters['manufacturer'] ?? '',
                'manufacturer_id'     => $parameters['manufacturer_id'] ?? '',
                'price'               => $parameters['price'] ?? '',
                'workflow'            => $parameters['workflow'] ?? '',
                'it'                  => $parameters['estimate_it_amount'] ?? '0.00',
                'project_num'         => $parameters['project_number'] ?? '',
                'cycle'               => $parameters['cycle'] ?? '',
                'start_up'            => $parameters['start_date'],
                'check_time'          => $parameters['check_date'],
                'is_big_file'         => $parameters['is_big_file'] ? '是' : '否',
                'is_net'              => $parameters['is_net'] ? '是' : '否',
                'is_netted'           => $parameters['is_netted'] ? '是' : '否',
                'is_other'            => $parameters['is_other'] ? '是' : '否',
                'data_save_req'       => $parameters['data_save_request']  ?? '',
                'reliable_req'        => $parameters['reliable_request'] ?? ''
            ];

            AssessmentReqDevSpilt::where('WF_OrUnid',$parameters['assess_id'])
                ->update($data);

            return customer_return_success('success');
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 编辑实施内容异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * 工作量评估创建
     * @param array $parameters
     * @return array
     */
    public function createWorkAssess(array $parameters) : array
    {
        $data = AssessmentReqDevSpilt::where('WF_OrUnid',$parameters['assess_id'])
            ->first();

        if (is_null($data)) {
            return customer_return_error('assess_id 异常');
        }

        $data = $data->toArray();

        $data['WF_OrUnid']           = Str::uuid()->toString();
        $data['implement_common']    = $parameters['implement_content'];
        $data['implement_common_id'] = $parameters['implement_content_id'];
        $data['function_name']       = $parameters['function_name'];
        $data['source_type']         = $parameters['source_type'];
        $data['source_type_id']      = $parameters['source_type_id'];
        $data['manufacturer']        = $parameters['manufacturer'] ?? '';
        $data['manufacturer_id']     = $parameters['manufacturer_id'] ?? '';
        $data['price']               = $parameters['price'] ?? '';
        $data['workflow']            = $parameters['workflow'] ?? '';
        $data['it']                  = $parameters['estimate_it_amount'] ?? '0.00';
        $data['project_num']         = $parameters['project_number'] ?? '';
        $data['cycle']               = $parameters['cycle'] ?? '';
        $data['start_up']            = $parameters['start_date'];
        $data['check_time']          = $parameters['check_date'];
        $data['is_big_file']         = $parameters['is_big_file'] ? '是' : '否';
        $data['is_net']              = $parameters['is_net'] ? '是' : '否';
        $data['is_netted']           = $parameters['is_netted'] ? '是' : '否';
        $data['is_other']            = $parameters['is_other'] ? '是' : '否';
        $data['data_save_req']       = $parameters['data_save_request']  ?? '';
        $data['reliable_req']        = $parameters['reliable_request'] ?? '' ;

        AssessmentReqDevSpilt::insert($data);

        return customer_return_success('创建成功');
    }

    /**
     * 删除实施内容
     * @param array $parameters
     * @return array
     */
    public function destroyWorkAssess(array $parameters): array
    {
        try{
            $count = AssessmentReqDevSpilt::from('assessment_req_dev_spilt as ads')
                ->leftJoin('bpm_orguserlist as bo',function ($join){
                    return $join->on('bo.pmsUserId','=','ads.dev_name_id')
                        ->orOn('bo.pmsUserId', '=','ads.dev_name_id');
                })
                ->where('ads.instanceId',$parameters['server_id'])
                ->count();

            if ($count <= 1) {
                return customer_return_error('不能删除最后一条该涉及系统和开发人员数据');
            }

            $status = AssessmentReqDevSpilt::where('WF_OrUnid',$parameters['assess_id'])
                ->exists();

            if (!$status) {
                return customer_return_success('数据已经被删除');
            }

            AssessmentReqDevSpilt::where('WF_OrUnid',$parameters['assess_id'])
                ->delete();

            return customer_return_success('删除成功');
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 删除实施内容异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /** 获取到网络处硬件评估
     * @param string $id
     * @return array
     */
    public function getHardware(string $id) : array
    {
        try {
            $xmlData = BpmMaindata::where('WF_OrUnid',$id)
                ->value('XmlData');

            if (empty($xmlData)) {
                $xmlData = BpmArchivedData::where('WF_OrUnid',$id)
                    ->value('XmlData');

                if (empty($xmlData)) {
                    return customer_return_success('success',[]);
                }
            }

            $data = $this->formatXml($xmlData);
            $newDocUid = $data['newDocUid']??'';
            $databaseServerName = $data['comboBox58_show'] ?? '';

            if (empty($data)) {
                return customer_return_success('success',[]);
            }

            $resData = [
                'applicant' => [
                    'apply_date'       => (!isset($data['applyDate']) || empty($data['applyDate'])) ? '' : date('Y-m-d',strtotime( $data['applyDate'])),
                    'apply_username'   => $data['applyPerson'] ?? '',
                    'apply_department' => $data['applyDept_show'] ?? '',
                    'apply_phone'      => $data['applyPersonPhone'] ?? '',
                ]
            ];

            $result = OriginalFormatDocHardware::where('original_formatDoc_uid',$newDocUid)
                ->select([
                    'database_server_id',
                    'cpu_quantity',
                    'memory_quantity',
                    'database_expect_invest',
                    'application_server',
                    'application_server_invest',
                    'san_storage_space',
                    'san_storage_space_invest',
                    'nac_storage_sapce',
                    'nac_storage_sapce_invest',
                    'dmz_server',
                    'dmz_server_invest',
                    'dedicated_line_expect_invest',
                ])
                ->where('is_deleted',0)
                ->first();

            if (is_null($result)) {
                // 从xmldata里取数
                $resData['hardware'] = [
                    'database_server_id'           => $data['comboBox58'] ?? '',
                    'database_server_name'         => $data['comboBox58_show'] ?? '',
                    'cpu_quantity'                 => $data['text60'] ?? '',
                    'memory_quantity'              => $data['text62'] ?? '',
                    'database_expect_invest'       => $data['text59'] ?? '',
                    'application_server'           => $data['text61'] ?? '',
                    'application_server_invest'    => $data['text63'] ?? '',
                    'san_storage_space'            => $data['text64'] ?? '',
                    'san_storage_space_invest'     => $data['text66'] ?? '',
                    'nac_storage_space'            => $data['text65'] ?? '',
                    'nac_storage_space_invest'     => $data['text67'] ?? '',
                    'dmz_server'                   => $data['text68'] ?? '',
                    'dmz_server_invest'            => $data['text69'] ?? '',
                    'dedicated_line_expect_invest' => $data['text700'] ?? ''
                ];

                return customer_return_success('success',$resData);
            }

            $resData['hardware'] = [
                'database_server_id'           => $result->database_server_id,
                'database_server_name'         => $databaseServerName,
                'cpu_quantity'                 => $result->cpu_quantity,
                'memory_quantity'              => $result->memory_quantity,
                'database_expect_invest'       => $result->database_expect_invest,
                'application_server'           => $result->application_server,
                'application_server_invest'    => $result->application_server_invest,
                'san_storage_space'            => $result->san_storage_space,
                'san_storage_space_invest'     => $result->san_storage_space_invest,
                'nac_storage_space'            => $result->nac_storage_sapce,
                'nac_storage_space_invest'     => $result->nac_storage_sapce_invest,
                'dmz_server'                   => $result->dmz_server,
                'dmz_server_invest'            => $result->dmz_server_invest,
                'dedicated_line_expect_invest' => $result->dedicated_line_expect_invest,
            ];

            return customer_return_success('success',$resData);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 网络处硬件评估异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 创建 网络处硬件评估
     * @param array $parameters
     * @return array
     */
    public function createHardware(array $parameters): array
    {
        try{
            // 增加对主表xmlData的修改 start
            $xmlData = BpmMaindata::where('WF_OrUnid',$parameters['server_id'])
                ->value('XmlData');

            if (empty($xmlData)) {
                return customer_return_error('IT服务单识别有误，请重新进入IT服务单后操作');
            }

            $data = $this->formatXml($xmlData);

            $newDocUid = $data['newDocUid'];

            //设置网络处硬件评估信息
            $data['comboBox58']         = $parameters['database_server_id']; // 数据库服务器ID
            $data['comboBox58_show']    = $parameters['database_server_name']; // 数据库服务器ID
            $data['text59']             = $parameters['database_expect_invest']; // 数据库服务器预计投入（万元）
            $data['text60']             = $parameters['cpu_quantity'];  //CPU数量
            $data['text61']             = $parameters['application_server']; //应用服务器数量4C8（台）
            $data['text62']             = $parameters['memory_quantity'];  //内存数量
            $data['text63']             = $parameters['application_server_invest']; //应用服务器4C8预计投入（万元）
            $data['text64']             = $parameters['san_storage_space'];  //SAN存储空间（GB
            $data['text65']             = $parameters['nac_storage_space'];  //NAC储空间大小（GB）
            $data['text68']             = $parameters['dmz_server'];  //DMZ服务器（台）
            $data['text66']             = $parameters['san_storage_space_invest'];  //SAN存储空间预计投入（万元）
            $data['text67']             = $parameters['nac_storage_space_invest'];  //NAC存储空间预计投入（万元）
            $data['text69']             = $parameters['dmz_server_invest'];  //DMZ服务器预计投入（万元）
            $data['text700']            = $parameters['dedicated_line_expect_invest'];  //专线预计投入（万元）

            $xml = $this->formatArray($data);

            BpmMaindata::where('WF_OrUnid',$parameters['server_id'])
                ->update([
                    'XmlData' => $xml
                ]);
            // 增加对主表xmlData的修改 end

            $data = OriginalFormatDocHardware::where('original_formatDoc_uid',$newDocUid)
                ->first();

            if (is_null($data)) {
                OriginalFormatDocHardware::insert([
                    'original_formatDoc_uid'        => $newDocUid,
                    'hardware_uid'                  => Str::uuid()->toString(),
                    'database_server_id'            => $parameters['database_server_id'],
                    'cpu_quantity'                  => $parameters['cpu_quantity'],
                    'memory_quantity'               => $parameters['memory_quantity'],
                    'database_expect_invest'        => $parameters['database_expect_invest'],
                    'application_server'            => $parameters['application_server'],
                    'application_server_invest'     => $parameters['application_server_invest'],
                    'san_storage_space'             => $parameters['san_storage_space'],
                    'san_storage_space_invest'      => $parameters['san_storage_space_invest'],
                    'nac_storage_sapce'             => $parameters['nac_storage_space'],
                    'nac_storage_sapce_invest'      => $parameters['nac_storage_space_invest'],
                    'dmz_server'                    => $parameters['dmz_server'],
                    'dmz_server_invest'             => $parameters['dmz_server_invest'],
                    'dedicated_line_expect_invest'  => $parameters['dedicated_line_expect_invest'],
                ]);
            } else {
                OriginalFormatDocHardware::where('original_formatDoc_uid',$newDocUid)
                    ->update([
                        'database_server_id'            => $parameters['database_server_id'],
                        'cpu_quantity'                  => $parameters['cpu_quantity'],
                        'memory_quantity'               => $parameters['memory_quantity'],
                        'database_expect_invest'        => $parameters['database_expect_invest'],
                        'application_server'            => $parameters['application_server'],
                        'application_server_invest'     => $parameters['application_server_invest'],
                        'san_storage_space'             => $parameters['san_storage_space'],
                        'san_storage_space_invest'      => $parameters['san_storage_space_invest'],
                        'nac_storage_sapce'             => $parameters['nac_storage_space'],
                        'nac_storage_sapce_invest'      => $parameters['nac_storage_space_invest'],
                        'dmz_server'                    => $parameters['dmz_server'],
                        'dmz_server_invest'             => $parameters['dmz_server_invest'],
                        'dedicated_line_expect_invest'  => $parameters['dedicated_line_expect_invest'],
                    ]);
            }

            return customer_return_success('操作成功');
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 网络处硬件评估创建异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * 网络处硬件评估数据库服务器列表
     * @return array
     */
    public function getHardwareServer(): array
    {
        try{
            $data = SOriginalFormatHardwareServer::where('is_candelete',0)
                ->get()
                ->map(function ($item){
                    return [
                        'id'      => $item->id,
                        'value'   => $item->name,
                        'default' => $item->is_default == 1
                    ];
                })
                ->toArray();

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 网络硬件评估 数据库服务器异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 需求评估汇总列表信息
     * @param string $id
     * @return array
     */
    public function getRequirement(string $id) : array
    {
        try{
            $sql = "SELECT DISTINCT
                dev_office,
                plate_name,
                invovle_sys,
                source_type,
                source_type_id,
                implement_common,
                SUM( CAST( workflow AS DECIMAL ( 18, 2 ) ) ) AS workflow,
                SUM( CAST( it AS DECIMAL ( 18, 2 ) ) ) AS it
            FROM
                assessment_req_dev_spilt ads
            WHERE
                ads.instanceId = '".$id."'
                AND ads.it IS NOT NULL
                AND ads.it != ''
            GROUP BY
                ads.implement_common_id,
                ads.invovle_sys_id,
                ads.source_type,
                ads.source_type_id";

            $data = DB::connection('bpm_rs')->select($sql);

            $data = array_map(function ($item){
                return [
                    'involve_plate'    => $item->plate_name ?? '',
                    'involve_office'   => $item->dev_office ?? '',
                    'involve_system'   => $item->invovle_sys ?? '',
                    'involve_content'  => $item->implement_common ?? '',
                    'source_type'      => $item->source_type ?? '',
                    'source_type_id'   => $item->source_type_id ?? '',
                    'workflow'         => $item->workflow ?? '0.0',
                    'it'               => $item->it ?? '0.0'
                ];
            },$data);

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 需求汇总异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * it 服务单 需求分析列表
     * @param string $id
     * @return array
     */
    public function getRequirementAnalysis(string $id, $pShowAll = 0, $pNodeId = '') : array
    {
        try{
            $showAll = 1;
            if($pShowAll == 0) {
                if(empty($pNodeId)) {
                    $nodeString = BpmMaindata::where('WF_OrUnid', $id)
                        ->value('WF_CurrentNodeid');

                    if (empty($nodeString)) {
                        $showAll = 1;
                    }

                    $nodeIdArray = explode(",", $nodeString);

                    $nodeIdArray = array_filter($nodeIdArray, function ($item) {
                        return substr($item, 0, 1) == 'T';
                    });

                    foreach ($nodeIdArray as $nodeId) {
                        if (in_array($nodeId, ['T10088'])) {
                            $showAll = 0;  // 若当前节点为“T10088需求分析”，则只返回当前登陆人相关的需求分析
                            break;
                        }
                    }
                }else{
                    if($pNodeId == 'T10088'){
                        $showAll = 0;  // 若当前节点为“T10088需求分析”，则只返回当前登陆人相关的需求分析
                    }
                }
            }

            if($showAll == 0) {
                $result = AssessmentReqConfirm::where('instanceId', $id)
                    ->where('WF_AddName', $this->getUsername())
                    ->select([
                        'WF_OrUnid',
                        'invovle_system_id',
                        'invovle_system_name',
                        'is_confirm',
                        'demand_specification',
                        'advice_confirm_time',
                        'expect_acceptance_time'
                    ])
                    ->get()
                    ->map(function ($item) {
                        return [
                            'id' => $item->WF_OrUnid,
                            'involve_system_id' => $item->invovle_system_id,
                            'involve_system_name' => $item->invovle_system_name,
                            'is_confirm' => $item->is_confirm == 1,
                            'demand_specification' => $item->demand_specification,
                            'advice_confirm_time' => $item->advice_confirm_time,
                            'expect_acceptance_time' => $item->expect_acceptance_time
                        ];
                    })
                    ->toArray();
            }else{
                $result = AssessmentReqConfirm::where('instanceId', $id)
                    ->select([
                        'WF_OrUnid',
                        'invovle_system_id',
                        'invovle_system_name',
                        'is_confirm',
                        'demand_specification',
                        'advice_confirm_time',
                        'expect_acceptance_time'
                    ])
                    ->get()
                    ->map(function ($item) {
                        return [
                            'id' => $item->WF_OrUnid,
                            'involve_system_id' => $item->invovle_system_id,
                            'involve_system_name' => $item->invovle_system_name,
                            'is_confirm' => $item->is_confirm == 1,
                            'demand_specification' => $item->demand_specification,
                            'advice_confirm_time' => $item->advice_confirm_time,
                            'expect_acceptance_time' => $item->expect_acceptance_time
                        ];
                    })
                    ->toArray();
            }

            return customer_return_success('success',$result);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 需求分析列表异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * it 服务单 初始化需求分析数据
     * @param array $parameters
     * @return array
     */
    public function initRequirementAnalysis(array $parameters) : array
    {
        try{
            //先删除需求分析
            AssessmentReqConfirm::where('instanceId', $parameters['server_id'])->delete();
            //查询需求分解
            $list = AssessmentReqDevSpilt::from('assessment_req_dev_spilt as ads')
                ->where('ads.instanceId',$parameters['server_id'])
                ->where('ads.implement_common', '!=' ,'不涉及调整')
                ->select([
                    'ads.invovle_sys_id',
                    'ads.invovle_sys',
                    'ads.dev_name_id'
                ])
                ->get()
                ->map(function ($item){
                    return [
                        'invovle_sys_id'    => $item->invovle_sys_id,
                        'invovle_sys'       => $item->invovle_sys,
                        'dev_name_id'       => $item->dev_name_id
                    ];
                })
                ->toArray();
            // 初始化需求分析
            if(!empty($list)) {
                foreach ($list as $l) {
                    $devUser = User::where('id',$l['dev_name_id'])
                        ->first();

                    AssessmentReqConfirm::insert([
                        'instanceId'            => $parameters['server_id'],
                        'WF_OrUnid'             => Str::uuid()->toString(),
                        'invovle_system_id'     => $l['invovle_sys_id'],
                        'invovle_system_name'   => $l['invovle_sys'],
                        'WF_AddName'            => $devUser->username ?? '',
                        'WF_AddName_CN'         => $devUser->person->name ?? '',
                        'is_confirm'            => 1
                    ]);
                }
            }

            return customer_return_success('操作成功',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 初始化需求分析异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }
    /**
     * it 服务单 需求分析填报
     * @param array $parameters
     * @return array
     */
    public function editRequirementAnalysis(array $parameters) : array
    {
        try{
            AssessmentReqConfirm::where('WF_OrUnid',$parameters['server_analysis_id'])
                ->update([
                    'is_confirm'             => $parameters['is_confirm'] ? 1 : 2,
                    'demand_specification'   => $parameters['demand_specification'],
                    'advice_confirm_time'    => $parameters['advice_confirm_time'],
                    'expect_acceptance_time' => $parameters['expect_acceptance_time']
                ]);

            return customer_return_success('操作成功',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 需求分析填报异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }



    /**
     * it 服务单 初始化用户验收
     * @param array $parameters
     * @return array
     */
    public function initSystemHarvest(array $parameters) : array
    {
        try{
            //先删除用户验收数据
            AssessmentUserAcceptance::where('instanceId', $parameters['server_id'])->delete();
            //查询需求分解
            $list = AssessmentReqDevSpilt::from('assessment_req_dev_spilt as ads')
                ->where('ads.instanceId',$parameters['server_id'])
                ->where('ads.implement_common', '!=' ,'不涉及调整')
                ->select([
                    'ads.invovle_sys_id',
                    'ads.invovle_sys',
                    'ads.dev_name_id'
                ])
                ->get()
                ->map(function ($item){
                    return [
                        'invovle_sys_id'    => $item->invovle_sys_id,
                        'invovle_sys'       => $item->invovle_sys,
                        'dev_name_id'       => $item->dev_name_id
                    ];
                })
                ->toArray();
            // 初始化用户验收数据
            if(!empty($list)) {
                foreach ($list as $l) {
                    $devUser = User::where('id',$l['dev_name_id'])
                        ->first();

                    if (AssessmentUserAcceptance::where('instanceId', $parameters['server_id'])
                        ->where('invovle_system_id', $l['invovle_sys_id'])
                        ->where('WF_AddName', $devUser->username)
                        ->doesntExist()) {

                        AssessmentUserAcceptance::insert([
                            'instanceId'            => $parameters['server_id'],
                            'WF_OrUnid'             => Str::uuid()->toString(),
                            'invovle_system_id'     => $l['invovle_sys_id'],
                            'invovle_system_name'   => $l['invovle_sys'],
                            'WF_AddName'            => $devUser->username ?? '',
                            'WF_AddName_CN'         => $devUser->person->name ?? ''
                        ]);
                    }
                }
            }

            return customer_return_success('操作成功',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 初始化用户验收异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /** it 服务单 用户验收列表
     * @param string $id
     * @return array
     */
    public function getSystemHarvest(string $id, $pShowAll = 0, $pNodeId = '') : array
    {
        try{
            $showAll = 1;
            if($pShowAll == 0) {
                if(empty($pNodeId)) {
                    $nodeString = BpmMaindata::where('WF_OrUnid', $id)
                        ->value('WF_CurrentNodeid');

                    if (empty($nodeString)) {
                        $showAll = 1;
                    }

                    $nodeIdArray = explode(",", $nodeString);

                    $nodeIdArray = array_filter($nodeIdArray, function ($item) {
                        return substr($item, 0, 1) == 'T';
                    });

                    foreach ($nodeIdArray as $nodeId) {
                        if (in_array($nodeId, ['T10120'])) {
                            $showAll = 0;  // 若当前节点为“T10120需求实施”，则只返回当前登陆人相关的用户验收清单
                            break;
                        }
                    }
                }else{
                    if($pNodeId == 'T10120'){
                        $showAll = 0;  // 若当前节点为“T10120需求实施”，则只返回当前登陆人相关的用户验收清单
                    }
                }
            }

            if($showAll == 0) {
                $result = AssessmentReqConfirm::where('assessment_req_confirm.instanceId', $id)
                    ->where('assessment_req_confirm.WF_AddName', $this->getUsername())
//                    ->leftJoin('assessment_user_acceptance as auc', 'auc.instanceId', '=', 'assessment_req_confirm.instanceId')
                    ->leftJoin('assessment_user_acceptance as auc',function ($join){
                        return $join->on('auc.instanceId', '=', 'assessment_req_confirm.instanceId')
                                    ->on('auc.WF_AddName', '=', 'assessment_req_confirm.WF_AddName');
                    })
                    ->select(
                        DB::raw('IFNULL(assessment_req_confirm.invovle_system_id, auc.invovle_system_id) as invovle_system_id, IFNULL(assessment_req_confirm.invovle_system_name, auc.invovle_system_name) as invovle_system_name'),
                        'auc.WF_OrUnid',
                        'auc.address',
                        'auc.username',
                        'auc.password',
                        'auc.instruction'
                    )
                    ->get()
                    ->map(function ($item) {
                        return [
                            'id' => $item->WF_OrUnid,
                            'involve_system_id' => $item->invovle_system_id,
                            'involve_system_name' => $item->invovle_system_name,
                            'address' => $item->address,
                            'username' => $item->username,
                            'password' => $item->password,
                            'instruction' => $item->instruction
                        ];
                    })
                    ->toArray();
            }else{
                $result = AssessmentReqConfirm::where('assessment_req_confirm.instanceId', $id)
                    ->leftJoin('assessment_user_acceptance as auc',function ($join){
                        return $join->on('auc.instanceId', '=', 'assessment_req_confirm.instanceId')
                                    ->on('auc.WF_AddName', '=', 'assessment_req_confirm.WF_AddName');
                    })
                    ->select(
                        DB::raw('IFNULL(assessment_req_confirm.invovle_system_id, auc.invovle_system_id) as invovle_system_id, IFNULL(assessment_req_confirm.invovle_system_name, auc.invovle_system_name) as invovle_system_name'),
                        'auc.WF_OrUnid',
                        'auc.address',
                        'auc.username',
                        'auc.password',
                        'auc.instruction'
                    )
                    ->get()
                    ->map(function ($item) {
                        return [
                            'id' => $item->WF_OrUnid,
                            'involve_system_id' => $item->invovle_system_id,
                            'involve_system_name' => $item->invovle_system_name,
                            'address' => $item->address,
                            'username' => $item->username,
                            'password' => $item->password,
                            'instruction' => $item->instruction
                        ];
                    })
                    ->toArray();

            }
//            $result = AssessmentUserAcceptance::where('instanceId',$id)
//                ->where('WF_AddName',$this->getUsername())
//                ->select([
//                    'WF_OrUnid',
//                    'invovle_system_name',
//                    'address',
//                    'username',
//                    'password',
//                    'instruction'
//                ])
//                ->get()
//                ->map(function ($item){
//                    return [
//                        'id'                  => $item->WF_OrUnid,
//                        'involve_system_name' => $item->invovle_system_name,
//                        'address'             => $item->address,
//                        'username'            => $item->username,
//                        'password'            => $item->password,
//                        'instruction'         => $item->instruction
//                    ];
//                })
//                ->toArray();


            return customer_return_success('success',$result);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 用户验收异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * it 服务单 用户验收填报
     * @param array $parameters
     * @return array
     */
    public function editSystemHarvest(array $parameters) : array
    {
        try{
            if(AssessmentUserAcceptance::where('WF_OrUnid',$parameters['server_harvest_id'])->exists()) {
                AssessmentUserAcceptance::where('WF_OrUnid', $parameters['server_harvest_id'])
                    ->update([
                        'address' => $parameters['address'],
                        'username' => $parameters['username'],
                        'password' => $parameters['password'],
                        'instruction' => $parameters['instruction']
                    ]);
            }else{
                AssessmentUserAcceptance::insert([
                    'instanceId'            => $parameters['server_id'],
                    'WF_OrUnid'             => Str::uuid()->toString(),
                    'invovle_system_id'     => $parameters['involve_system_id'],
                    'invovle_system_name'   => $parameters['involve_system_name'],
                    'WF_AddName'            => $this->getUsername(),
                    'WF_AddName_CN'         => auth('api')->user()->person->name,
                    'address'               => $parameters['address'],
                    'username'              => $parameters['username'],
                    'password'              => $parameters['password'],
                    'instruction'           => $parameters['instruction']
                ]);
            }

            return customer_return_success('操作成功',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 用户验收填报异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }


    /**
     * it 服务单 获取建议用户确认反馈时间
     * @param array $parameters
     * @return array
     */
    public function getPersonDate(array $parameters) : array
    {
        try {
            $data = $this->getXmlToArrayById($parameters['server_id']);

            return customer_return_success('success',['person_date'=>$data['person_date'] ?? '']);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT服务单 查询建议用户确认反馈时间 异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * it 服务单 更新建议用户确认反馈时间
     * @param array $parameters
     * @return array
     */
    public function editPersonDate(array $parameters) : array
    {
        try {
            $data = $this->getXmlToArrayById($parameters['server_id']);
            $data['person_date'] = $parameters['person_date'];

            $xml = $this->getArrayToXmlByArray($data);

            BpmMaindata::where('WF_OrUnid',$parameters['server_id'])
                ->update([
                    'XmlData' => $xml
                ]);

            return customer_return_success('操作成功',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT服务单 更新建议用户确认反馈时间 异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * it 服务单 初始化上线列表
     * @param array $parameters
     * @return array
     */
    public function initSystemOnline(array $parameters) : array
    {
        try{
            //先删除上线列表
            AssessmentOnlineInformation::where('instanceId', $parameters['server_id'])->delete();
            //查询需求分解
            $list = AssessmentReqDevSpilt::from('assessment_req_dev_spilt as ads')
                ->where('ads.instanceId',$parameters['server_id'])
                ->where('ads.implement_common', '!=' ,'不涉及调整')
                ->select([
                    'ads.invovle_sys_id',
                    'ads.invovle_sys',
                    'ads.dev_name_id',
                    'ads.dev_name'
                ])
                ->groupBy('invovle_sys_id')
                ->get()
                ->map(function ($item){
                    return [
                        'invovle_sys_id'    => $item->invovle_sys_id,
                        'invovle_sys'       => $item->invovle_sys,
                        'dev_name_id'       => $item->dev_name_id,
                        'dev_name'          => $item->dev_name
                    ];
                })
                ->toArray();
            // 初始化上线列表
            if(!empty($list)) {
                foreach ($list as $l) {
                    $devUser = User::where('id',$l['dev_name_id'])
                        ->first();

                    AssessmentOnlineInformation::insert([
                        'instanceId'                => $parameters['server_id'],
                        'WF_OrUnid'                 => Str::uuid()->toString(),
                        'invovle_system_id'         => $l['invovle_sys_id'],
                        'invovle_system_name'       => $l['invovle_sys'],
                        'responsible_person_id'     => $l['dev_name_id'],
                        'responsible_person_name'   => $l['dev_name'],
                        'WF_AddName'                => $devUser->username ?? '',
                        'WF_AddName_CN'             => $devUser->person->name ?? ''
                    ]);
                }
            }

            return customer_return_success('操作成功',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 初始化需求分析异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * it 服务单 上线列表
     * @param string $id
     * @return array
     */
    public function getSystemOnline(string $id, $pShowAll = 0, $pNodeId = '') : array
    {
        try {
            $showAll = 1;
            if($pShowAll == 0) {
                if(empty($pNodeId)) {
                    $nodeString = BpmMaindata::where('WF_OrUnid', $id)
                        ->value('WF_CurrentNodeid');

                    if (empty($nodeString)) {
                        $showAll = 1;
                    }

                    $nodeIdArray = explode(",", $nodeString);

                    $nodeIdArray = array_filter($nodeIdArray, function ($item) {
                        return substr($item, 0, 1) == 'T';
                    });

                    foreach ($nodeIdArray as $nodeId) {
                        if (in_array($nodeId, ['T10104'])) {
                            $showAll = 0;  // 若当前节点为“T10104准备发布”，则只返回当前登陆人相关的上线信息
                            break;
                        }
                    }
                }else{
                    if($pNodeId == 'T10104'){
                        $showAll = 0;  // 若当前节点为“T10104准备发布”，则只返回当前登陆人相关的上线信息
                    }
                }
            }

            if($showAll == 0) {
                $result = AssessmentReqConfirm::where('assessment_req_confirm.instanceId', $id)
                    ->where('assessment_req_confirm.WF_AddName', $this->getUsername())
                    ->leftJoin('assessment_online_information as aoi', function ($join){
                        return $join->on('aoi.instanceId', '=', 'assessment_req_confirm.instanceId')
                            ->on('aoi.WF_AddName', '=', 'assessment_req_confirm.WF_AddName');
                    })
                    ->leftJoin('pms.user', 'user.username', '=', 'assessment_req_confirm.WF_AddName')
                    ->leftJoin('pms.person', 'person.id', '=', 'user.id')
                    ->select(
                        DB::raw('IFNULL(assessment_req_confirm.invovle_system_name, aoi.invovle_system_name) as involve_system_name, IFNULL(aoi.responsible_person_name, person.name) as responsible_person_name'),
                        'aoi.WF_OrUnid',
                        'aoi.is_online',
                        'aoi.online_date',
                    )
                    ->get()
                    ->map(function ($item) {
                        return [
                            'id' => $item->WF_OrUnid,
                            'involve_system_name' => $item->involve_system_name,
                            'responsible_person_name' => $item->responsible_person_name,
                            'is_online' => $item->is_online == 1,
                            'online_date' => $item->online_date,
                        ];
                    })
                    ->toArray();
            }else{
                $result = AssessmentReqConfirm::where('assessment_req_confirm.instanceId', $id)
                    ->leftJoin('assessment_online_information as aoi',function ($join){
                        return $join->on('aoi.instanceId', '=', 'assessment_req_confirm.instanceId')
                            ->on('aoi.WF_AddName', '=', 'assessment_req_confirm.WF_AddName');
                    })
                    ->leftJoin('pms.user', 'user.username', '=', 'assessment_req_confirm.WF_AddName')
                    ->leftJoin('pms.person', 'person.id', '=', 'user.id')
                    ->select(
                        DB::raw('IFNULL(assessment_req_confirm.invovle_system_name, aoi.invovle_system_name) as involve_system_name, IFNULL(aoi.responsible_person_name, person.name) as responsible_person_name'),
                        'aoi.WF_OrUnid',
                        'aoi.is_online',
                        'aoi.online_date',
                    )
                    ->get()
                    ->map(function ($item) {
                        return [
                            'id' => $item->WF_OrUnid,
                            'involve_system_name' => $item->involve_system_name,
                            'responsible_person_name' => $item->responsible_person_name,
                            'is_online' => $item->is_online == 1,
                            'online_date' => $item->online_date,
                        ];
                    })
                    ->toArray();
            }
//            $result = AssessmentOnlineInformation::where('instanceId',$id)
//                ->where('WF_AddName',$this->getUsername())
//                ->select([
//                    'invovle_system_name as involve_system_name',
//                    'responsible_person_name',
//                    'is_online',
//                    'online_date',
//                    'WF_OrUnid'
//                ])
//                ->get()
//                ->map(function ($item){
//                    return [
//                        'id'                       => $item->WF_OrUnid,
//                        'involve_system_name'      => $item->involve_system_name,
//                        'responsible_person_name'  => $item->responsible_person_name,
//                        'is_online'                => $item->is_online == 1,
//                        'online_date'              => $item->online_date,
//                    ];
//                })
//                ->toArray();

            return customer_return_success('success',$result);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 上线信息异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * it 服务单 上线填报
     * @param array $parameters
     * @return array
     */
    public function editSystemOnline(array $parameters) : array
    {
        try{
            AssessmentOnlineInformation::where('WF_OrUnid',$parameters['server_online_id'])
                ->update([
                    'is_online'    => $parameters['is_online'] ? 1 : 2,
                    'online_date'  => $parameters['online_date']
                ]);

            return customer_return_success('操作成功',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 填报上线信息异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * 需求汇总 项目负责人
     * @param string $id
     * @return array
     */
    public function getRequirementHeadUser(string $id, $lead_team_id) : array
    {
        try {
//            $data = AssessmentReqDevSpilt::where('instanceId',$id)
//                ->select([
//                    'dev_name',
//                    'dev_name_id'
//                ])
//                ->distinct()
//                ->get()
//                ->map(function ($item){
//                    return [
//                        'id'   => $item->dev_name_id ?? 0,
//                        'name' => $item->dev_name ?? ''
//                    ];
//                })
//                ->toArray();
            $data = Person::where('unit_id', '=', $lead_team_id)
                ->where('is_deleted','=',0)
                ->select([
                    'id',
                    'name'
                ])
                ->orderBy('ord')
                ->get()
                ->toArray();

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 需求汇总 项目负责人异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /** 需求汇总 牵头单位
     * @return array
     */
    public function getRequirementHeadTeam() : array
    {
        try{
            $data = Unit::where('parent_id',375)
                ->where('is_deleted',0)
                ->select([
                    'id',
                    'name'
                ])
                ->distinct()
                ->orderBy('ord')
                ->get()
                ->toArray();

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 需求汇总 牵头单位异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 根据id 获取到xml中的数据
     * 将xml转换成array数组格式数据
     * @param string $id
     * @return array
     */
    public function getXmlToArrayById(string $id) : array
    {
        if (empty($id)) {
            return [];
        }

        $data = BpmMaindata::where('WF_OrUnid',$id)
            ->value('XmlData');

        if (empty($data)) {
            return [];
        }

        $array = XmlToArray::convert($data);

        if (!isset($array['WFItem']) || empty($array['WFItem'])) {
            return [];
        }

        $result = [];

        foreach ($array['WFItem'] as $value){
            if (isset($value['@attributes']['name']) && !empty($value['@attributes']['name'])) {
                $result[$value['@attributes']['name']] = $value['@content'] ?? null;
            }
        }

        return $result;
    }

    /**
     * 将数组转换成xml数据格式
     * @param array $array
     * @return string
     * @throws \DOMException
     */
    public function getArrayToXmlByArray(array $array) : string
    {
        if (empty($array)) {
            return '';
        }

        $result = [
            'WFItem' => []
        ];

        foreach ($array as $key => $value) {
            if (empty($value)) {
                $result['WFItem'][] = [
                    '@attributes' => [
                        'name' => $key
                    ]
                ];
            } else {
                $result['WFItem'][] = [
                    '@attributes' => [
                        'name' => $key,
                    ],
                    '@cdata' => $value
                ];
            }
        }

        $xml = new ArrayToXml($result,'Items');

        return $xml->dropXmlDeclaration()->toXml();
    }

    /**
     * 需求汇总 详情
     * @param string $id
     * @return array
     */
    public function getRequirementDetails(array $parameters) : array
    {
        try {
            $id = $parameters['server_id'];

            $data = $this->getXmlToArrayById($id);

            if (empty($data)) {
                return customer_return_error('数据不存在');
            }
            //查询IT服务单的 预计IT投入、立项金额
            $assess = AssessmentReqDevSpilt::from('assessment_req_dev_spilt as ads')
                ->where('ads.instanceId',$id)
                ->selectRaw(
                    'ads.it, case when ads.source_type_id = 2 then ads.it else 0 end it2'
                )
                ->get()
                ->map(function ($value){
                    return [
                        'it_amount' => floatval($value->it) ?: '0.00',
                        'it2'       => floatval($value->it2) ?: '0.00'
                    ];
                });

            //it金额
            $itTotalAmount = $assess->sum('it_amount');

            //立项金额
            // text59+text63+text66+text67+text69+text700
            $projectTotalAmount = $assess->sum('it2')
                + ($data['text59'] ?? 0)
                + ($data['text63'] ?? 0)
                + ($data['text66'] ?? 0)
                + ($data['text67'] ?? 0)
                + ($data['text69'] ?? 0)
                + ($data['text700'] ?? 0);
            // $data['leadDev_lead']  // 额外存储的牵头团队ID
            // 由牵头团队查询团队长ID和名称
            $leadTeam = Unit::where('unit.parent_id', 375)
                ->where('unit.is_deleted', 0)
                ->leftJoin('pms.person as p', 'p.unit_id', '=', 'unit.id')
                ->leftJoin('pms.r_person_post as rpp', 'p.id', '=', 'rpp.person_id')
                ->leftJoin('pms.user as us', 'us.person_id', '=', 'p.id')
                ->where('rpp.post_id', '!=', 9)
                ->where('p.is_deleted', 0)
                ->select([
                    'p.name',
                    'p.id',
                    DB::raw('unit.name as leader_team')
                ])
                ->where('unit.id', $data['dev_lead_id']??$data['leadDev_lead']??'')
                ->get()
                ->map(function ($item) {
                    return [
                        'leaderId'      => $item->id,
                        'leaderName'    => $item->name,
                        'leadTeamName'  => $item->leader_team,
                    ];
                })
                ->first();
            $projectLeaderId    = $data['comboBox73'] ?? '';
            $projectLeaderName  = $data['comboBox73_show'] ?? '';
            // 根据当前节点和牵头团队情况调整项目负责人的显示值
            if(isset($data['leadDev_lead']) && !empty($data['leadDev_lead'])
                && isset($parameters['node_id']) && !empty($parameters['node_id'])
                && ($parameters['node_id'] == 'T10017' || $parameters['node_id'] == 'T10082')){

                $projectLeaderId    = $leadTeam['leaderId'] ?? '';
                $projectLeaderName  = $leadTeam['leaderName'] ?? '';
            }

            // 计算涉及团队 和 系统负责人
            $involve_team_id    = $data['text99_id'] ?? '';
            $involve_team       = $data['text99'] ?? '';
            $system_leader_id   = $data['text999_id'] ?? '';
            $system_leader      = $data['text999'] ?? '';
            if((!isset($data['leadDev_lead']) || !empty($data['leadDev_lead']))
                && isset($parameters['node_id']) && !empty($parameters['node_id'])
                && ($parameters['node_id'] == 'T10017' || $parameters['node_id'] == 'T10082')){

                $list = AssessmentReqDevSpilt::from('assessment_req_dev_spilt as ads')
                    ->distinct()
                    ->where('ads.instanceId', $id)
                    ->where('ads.dev_office_id', '!=', $data['dev_lead_id']??$data['leadDev_lead']??'')  // 不为所选牵头团队
                    ->selectRaw('group_concat(ads.dev_name_id) as dev_name_id, group_concat(ads.dev_name) as dev_name, group_concat(ads.dev_office_id) as dev_office_id, group_concat(ads.dev_office) as dev_office')
                    ->orderBy('ord_id')
                    ->get()
                    ->map(function ($item) {
                        return [
                            'system_name_id'    => $item->dev_office_id,
                            'system_name'       => $item->dev_office,
                            'leader_id'         => $item->dev_name_id,
                            'leader'            => $item->dev_name
                        ];
                    })
                    ->first();

                $involve_team_id    = $list['system_name_id'] ?? '';
                $involve_team       = $list['system_name'] ?? '';
                $system_leader_id   = $list['leader_id'] ?? '';
                $system_leader      = $list['leader'] ?? '';
            }

            $result = [
                'id'                            => $id,
                'project_leader'                => $projectLeaderId,
                'project_leader_name'           => $projectLeaderName,
                'development_leader_team_id'    => $data['dev_lead_id'] ?? '',
                'development_leader_team'       => $leadTeam['leadTeamName'] ?? $data['dev_lead'] ?? '',  // dev_lead 可能存的是ID
                'involve_team_id'               => $involve_team_id,
                'involve_team'                  => $involve_team,
                'system_leader_id'              => $system_leader_id,
                'system_leader'                 => $system_leader,
                'estimate_it_amount'            => (($data['text76'] ?? '' )!='' ? $data['text76'] : $itTotalAmount) ?? $itTotalAmount,
                'project_amount'                => (($data['projectAmount'] ?? '')!='' ? $data['projectAmount'] : $projectTotalAmount) ?? $projectTotalAmount
            ];

            return customer_return_success('success',$result);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 需求汇总 详情异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 获取选择牵头团队之后的涉及团队、系统负责人人 两个字符串
     * @param $serverId 服务单ID
     * @param $leadTeamID 已选牵头团队ID
     * @return array
     */
    public function getRelatedTeamAndSystemLeaderStr($serverId, $leadTeamID):array
    {
        try {
            $list = AssessmentReqDevSpilt::from('assessment_req_dev_spilt as ads')
                ->distinct()
                ->where('ads.instanceId', $serverId)
                ->where('ads.dev_office_id', '!=', $leadTeamID)  // 不为所选牵头团队
//                ->select([
//                    'ads.dev_name',
//                    'ads.dev_office',    // 团队名称
//                ])
                ->selectRaw('group_concat(ads.dev_name_id) as dev_name_id, group_concat(ads.dev_name) as dev_name, group_concat(ads.dev_office_id) as dev_office_id, group_concat(ads.dev_office) as dev_office')
                ->orderBy('ord_id')
                ->get()
                ->map(function ($item) {
                    return [
                        'system_name_id'    => $item->dev_office_id,
                        'system_name'       => $item->dev_office,
                        'leader_id'         => $item->dev_name_id,
                        'leader'            => $item->dev_name
                    ];
                })
                ->toArray();

            return customer_return_success('success',$list);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 需求分解 获取项目负责人异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 需求汇总 修改项目负责人和开发牵头单位
     * @param array $parameters
     * @return array
     */
    public function requirementDetailsEdit(array $parameters) : array
    {
        try {
            $data = $this->getXmlToArrayById($parameters['server_id']);

//            $list = AssessmentReqDevSpilt::from('assessment_req_dev_spilt as ads')
//                ->distinct()
//                ->where('ads.instanceId',$parameters['server_id'])
//                ->where(function ($query){
//                    return $query->where('ads.spilt_return',1)
//                        ->orWhere('ads.spilt_return',0);
//                })
//                ->select([
//                    'ads.WF_OrUnid',
//                    'ads.plate_name',
//                    'ads.invovle_sys',
//                    'ads.dev_name'
//                ])
//                ->orderBy('ord_id')
//                ->get()
//                ->map(function ($item){
//                    return [
//                        'id'          => $item->WF_OrUnid,
//                        'plate_name'  => $item->plate_name,
//                        'system_name' => $item->invovle_sys,
//                        'leader'      => $item->dev_name
//                    ];
//                })
//                ->toArray();
            if($parameters['changed'] == 1) {
                // 由牵头团队查询团队长ID和名称
                $leadTeam = Unit::where('unit.parent_id', 375)
                    ->where('unit.is_deleted', 0)
                    ->leftJoin('pms.person as p', 'p.unit_id', '=', 'unit.id')
                    ->leftJoin('pms.r_person_post as rpp', 'p.id', '=', 'rpp.person_id')
                    ->leftJoin('pms.user as us', 'us.person_id', '=', 'p.id')
                    ->where('rpp.post_id', '!=', 9)
                    ->where('p.is_deleted', 0)
                    ->select([
                        'unit.id',
                        'unit.name',
                        'us.username',
                        DB::raw('p.name as leader_name')
                    ])
                    ->where('unit.id', $parameters['development_leader_team_id'])
                    ->get()
                    ->map(function ($item) {
                        return [
                            'leadTeamID' => $item->id,
                            'leadTeamName' => $item->name,
                            'leadUserName' => $item->username,
                            'leaderName' => $item->leader_name,
                        ];
                    })
                    ->first();

                $data['comboBox73'] = $parameters['project_leader_id'];           // 项目负责人ID
                $data['comboBox73_show'] = $parameters['project_leader'];              // 项目负责人名称
                $data['dev_lead_id'] = $parameters['development_leader_team_id'];  // 牵头团队ID
                $data['dev_lead'] = $parameters['development_leader_team'];     // 牵头团队名称
                $data['dev_lead_show'] = $parameters['development_leader_team'];     // 牵头团队名称，额外存储

                $data['leadDev_lead'] = $parameters['development_leader_team_id'];  // 牵头团队ID，额外存储


                $data['text99_id'] = $parameters['system_name_id'] ?? '';     // 涉及团队ID，多个以逗号分隔
                $data['text99'] = $parameters['system_name'] ?? '';     // 涉及团队名称，多个以逗号分隔
                $data['text999_id'] = $parameters['leader_id'] ?? '';     // 系统负责人ID，多个以逗号分隔
                $data['text999'] = $parameters['leader'] ?? '';     // 系统负责人名称，多个以逗号分隔


                //设置需求分解处牵头单位信息
                $data['leadTeam'] = $parameters['development_leader_team_id'];   // 牵头团队ID
                $data['leadTeam_show'] = $parameters['development_leader_team'];   // 牵头团队名称
//                $data['involvedSystem'] = '';                   // 涉及系统置空，更新，不再修改涉及系统
                $data['leader'] = $leadTeam['leadUserName'] ?? '';   // 牵头团队长ID
                $data['leader_show'] = $leadTeam['leaderName'] ?? '';   // 牵头团队长名称
            }
            //查询IT服务单的 预计IT投入、立项金额
            $assess = AssessmentReqDevSpilt::from('assessment_req_dev_spilt as ads')
                ->where('ads.instanceId',$parameters['server_id'])
                ->selectRaw(
                    'ads.it, case when ads.source_type_id = 2 then ads.it else 0 end it2'
                )
                ->get()
                ->map(function ($value){
                    return [
                        'it_amount' => floatval($value->it) ?: '0.00',
                        'it2'       => floatval($value->it2) ?: '0.00'
                    ];
                });

            //it金额
            $itTotalAmount = $assess->sum('it_amount');

            //立项金额
            // $assess->sum('it2') + text59+text63+text66+text67+text69+text700
            $allIT = $assess->sum('it2');
            // 设置其他信息
            $data['text76']         = $parameters['text76']??$itTotalAmount;   // 预计IT投入
            $data['projectAmount']  = $parameters['projectAmount']??($allIT + ($data['text59'] ?? 0)
                    + ($data['text63'] ?? 0)
                    + ($data['text66'] ?? 0)
                    + ($data['text67'] ?? 0)
                    + ($data['text69'] ?? 0)
                    + ($data['text700'] ?? 0) );   // 立项金额

            $data['allHareword']  = (string)(($data['text59'] ?? 0)
                    + ($data['text63'] ?? 0)
                    + ($data['text66'] ?? 0)
                    + ($data['text67'] ?? 0)
                    + ($data['text69'] ?? 0)
                    + ($data['text700'] ?? 0))??'';
            $data['allIt']  = (string)$allIT ?? '';
            $data['allProject']  = (string)($allIT + ($data['text59'] ?? 0)
                + ($data['text63'] ?? 0)
                + ($data['text66'] ?? 0)
                + ($data['text67'] ?? 0)
                + ($data['text69'] ?? 0)
                + ($data['text700'] ?? 0) )??'';

            $xml = $this->getArrayToXmlByArray($data);

            BpmMaindata::where('WF_OrUnid',$parameters['server_id'])
                ->update([
                    'XmlData' => $xml
                ]);

            return customer_return_success('success',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 服务单 需求汇总 修改项目负责人和开发牵头单位异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 需求分解 获取项目负责人
     * @param string $id
     * @return array
     */
    public function getTaskDecomposeProjectLeader(string $id) : array
    {
        try {
            $array = $this->getXmlToArrayById($id);
            $leadTeam = $array['leadTeam'] ?? 0;

            if (!$leadTeam) {
                return customer_return_success('success',[]);
            }

            $data = Person::where('is_deleted',0)
                ->where('unit_id',$leadTeam)
                ->select([
                    'id',
                    'name'
                ])
                ->distinct()
                ->get()
                ->toArray();

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 需求分解 获取项目负责人异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 设置服务单 项目负责人
     * @param array $parameters
     * @return array
     */
    public function editTaskDecomposeProjectLeader(array $parameters) : array
    {
        try {
            $data = $this->getXmlToArrayById($parameters['server_id']);
            $data['projectLeader'] = $parameters['user_id'];
            $data['projectLeader_show'] = $parameters['project_leader'];

            $xml = $this->getArrayToXmlByArray($data);

            BpmMaindata::where('WF_OrUnid',$parameters['server_id'])
                ->update([
                    'XmlData' => $xml
                ]);

            return customer_return_success('success',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT 需求分解 编辑项目负责人：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * it 服务单 架构审核 审核意见
     * @param array $parameters
     * @return array
     */
    public function architectureApproval(array $parameters) : array
    {
        try {
            $data = $this->getXmlToArrayById($parameters['server_id']);
            $data['archOpinions'] = $parameters['opinion'];

            $xml = $this->getArrayToXmlByArray($data);

            BpmMaindata::where('WF_OrUnid',$parameters['server_id'])
                ->update([
                    'XmlData' => $xml
                ]);

            return customer_return_success('审批完成',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT服务单 架构审核 架构审核意见 异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

    /**
     * 工作量评估节点审核人员选择
     * @param string $id
     * @return array
     */
    public function getWorkAssessUsers(string $id) : array
    {
        try {
            $data = $this->getXmlToArrayById($id);

            $username = $data['username'] ?? '';

            if (empty($username)) {
                return  customer_return_success('success',[]);
            }

            $result = AssessmentReqDevSpilt::where('instanceId',$id)
                ->where('leader_id',30000952)
                ->select([
                    'dev_name_id',
                    'dev_name'
                ])
                ->distinct()
                ->get()
                ->map(function ($item){
                    return [
                        'id'   => intval($item->dev_name_id ?? 0),
                        'name' => $item->dev_name ?? ''
                    ];
                })
                ->toArray();

            return customer_return_success('success',$result);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT服务单 工作量评估节点审核人员选择 异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 根据流程节点获取到页面展示的模块内容
     * @param string $nodeId
     * @return array
     */
    public function getShowModuleByNodeId(string $nodeId) : array
    {
        return [
            'requirement_decompose',
            'workload_assessment',
            'network_hardware',
            'system_online',
            'user_check',
            'requirement_analysis',
            'requirement_statistics'
        ];
    }


    /**
     * it 服务单 返回需求分析前置处理
     * @param array $parameters
     * @return array
     */
    public function backReqConfirm(array $parameters) : array
    {
        try {

            AssessmentReqConfirm::where('instanceId',$parameters['server_id'])
                ->whereIn('WF_OrUnid', explode(",",$parameters['doc_id']))
                ->update([
                    'is_return' => 1
                ]);

            return customer_return_success('操作完成',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT服务单 返回需求分析前置处理 异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }


    /**
     * it 服务单 返回需求实施前置处理
     * @param array $parameters
     * @return array
     */
    public function backUserAcceptance(array $parameters) : array
    {
        try {

            AssessmentUserAcceptance::where('instanceId',$parameters['server_id'])
                ->whereIn('WF_OrUnid', explode(",",$parameters['doc_id']))
                ->update([
                    'is_return' => 1
                ]);

            return customer_return_success('操作完成',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT服务单 返回需求实施前置处理 异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }


    /**
     * it 服务单 返回上线信息前置处理
     * @param array $parameters
     * @return array
     */
    public function backOnlineInfo(array $parameters) : array
    {
        try {

            AssessmentOnlineInformation::where('instanceId',$parameters['server_id'])
                ->whereIn('WF_OrUnid', explode(",",$parameters['doc_id']))
                ->update([
                    'is_return' => 1
                ]);

            return customer_return_success('操作完成',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('IT服务单 返回上线信息前置处理 异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('操作异常，请稍后再试');
        }
    }

}


